锘??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲最大黄色网站,日本亚洲欧美色视频在线播放,亚洲精品国产字幕久久不卡http://m.tkk7.com/dashi99/<div align="center"> <img height="50" width="200" name="welcome" src="http://m.tkk7.com/images/blogjava_net/majianan/14891/r_5858488902000cu2.gif"/> </div> <br/> <center><font size=4 >楸肩涓嶅紑姘?浣嗘槸娌℃湁璇翠笉紱誨紑鍝淮姘?</font></center>zh-cnSun, 11 May 2025 07:58:40 GMTSun, 11 May 2025 07:58:40 GMT60jvm瀛︿範絎旇http://m.tkk7.com/dashi99/archive/2012/12/14/393000.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Fri, 14 Dec 2012 07:32:00 GMThttp://m.tkk7.com/dashi99/archive/2012/12/14/393000.htmlhttp://m.tkk7.com/dashi99/comments/393000.htmlhttp://m.tkk7.com/dashi99/archive/2012/12/14/393000.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/393000.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/393000.htmlhttp://dl.iteye.com/upload/attachment/0077/7621/4698d147-570f-3fb8-a424-7e538cb587e4.bmp

銈炴矇榛樻槸閲戙倿 2012-12-14 15:32 鍙戣〃璇勮
]]>
ThreadPoolExecutor usage summaryhttp://m.tkk7.com/dashi99/archive/2012/11/27/392065.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Tue, 27 Nov 2012 05:43:00 GMThttp://m.tkk7.com/dashi99/archive/2012/11/27/392065.htmlhttp://m.tkk7.com/dashi99/comments/392065.htmlhttp://m.tkk7.com/dashi99/archive/2012/11/27/392065.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/392065.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/392065.html闃呰鍏ㄦ枃

銈炴矇榛樻槸閲戙倿 2012-11-27 13:43 鍙戣〃璇勮
]]>
How To Avoid javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated Problem Using Apache HttpClienthttp://m.tkk7.com/dashi99/archive/2012/08/14/385484.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Tue, 14 Aug 2012 10:42:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/14/385484.htmlhttp://m.tkk7.com/dashi99/comments/385484.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/14/385484.html#Feedback2http://m.tkk7.com/dashi99/comments/commentRss/385484.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/385484.html

I use Apache’s HttpClient library for all my URL related needs. It is a marvelous library that does most of the job behind the scenes. Compared the Java’s URL class, it is not as easy to use as Apache’s HttpClient. While using this library, a site that I commonly check for updates threw the exception message javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.

When I checked the site, it seemed that its SSL certificated had expired. The only workaround for this is to create your own TrustManager. This class actually checks if the SSL certificate is valid. The scheme used by SSL is called X.509 and Java has a specific TrustManager for this scheme, called X509TrustManager.

This handy method created by theskeleton is just the perfect solution to have your HttpClient object bypass any SSL related errors and ensures that it accepts all SSL certificates of a site, whether it is expired or not.


public static HttpClient wrapClient(HttpClient base) {
    
try {
        SSLContext ctx 
= SSLContext.getInstance("TLS");
        X509TrustManager tm 
= new X509TrustManager() {
            
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
 
            
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
 
            
public X509Certificate[] getAcceptedIssuers() {
                
return null;
            }
        };
        ctx.init(
nullnew TrustManager[]{tm}, null);
        SSLSocketFactory ssf 
= new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm 
= base.getConnectionManager();
        SchemeRegistry sr 
= ccm.getSchemeRegistry();
        sr.register(
new Scheme("https", ssf, 443));
        
return new DefaultHttpClient(ccm, base.getParams());
    } 
catch (Exception ex) {
        
return null;
    }
}

Another way is to recreate the keystore, for the keystore you should have the site in the CN=XXX.
the command as below:
1. Create keystore
keytool -genkey -dname "cn=daXXX.XXX.com,o=,c=" -storepass MB7BROKERpzn -keystore pznKeyStore.jks -alias pznsigned
2. Export the cert
keytool -export -keystore pznKeyStore.jks -alias pznsigned -file pznsslcert.cer
3. Create trust store for client
keytool -genkey -dname "cn=da957203.fmr.com,o=,c=" -storepass MB7BROKERpzn -keystore pznTrustStore.jks -alias pzntrustsigned
4. import the server cert
keytool -import -alias pzntrust -file pznsslcert.cer -keystore pznTrustStore.jks -storepass MB7BROKERpzn
5. use http client to call the server
        try {
            KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(new File(trustfname));
            try {
                trustStore.load(instream, passphrase.toCharArray());
            } finally {
                try { instream.close(); } catch (Exception ignore) {}
            }
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            Scheme sch = new Scheme("https", 443, socketFactory);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }







銈炴矇榛樻槸閲戙倿 2012-08-14 18:42 鍙戣〃璇勮
]]>
How to insert multiple record into DB with store procedure?http://m.tkk7.com/dashi99/archive/2012/08/13/385403.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 13 Aug 2012 08:17:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/13/385403.htmlhttp://m.tkk7.com/dashi99/comments/385403.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/13/385403.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/385403.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/385403.html

1.        1.Define the object type PROFILE_TAG_TYPE.

CREATE OR REPLACE TYPE PZN_ADMIN.PROFILE_TAG_TYPE

AS

 OBJECT

 (

    MID                     VARCHAR2 (34),

    TAG_ID                  NUMBER,

    CUSTOMER_TYPE           VARCHAR2(1),

    SOURCE_SYSTEM           VARCHAR2(30),

    TAG_CREATED_DATE        VARCHAR2(30),

    INTEREST_LEVEL          NUMBER(2),

    SUPPRESSION_IND         VARCHAR2(2),

    SUPPRESSION_EXPIRY_DATE VARCHAR2(30),

    LAST_HOUSEKEEPING_DATE VARCHAR2(30),

    LAST_EVENT_DATE         VARCHAR2(30),

REASON                  VARCHAR2(1500) );

 

2.       2. Grant PROFILE_TAG_TYPE execute access to PZN_MB_USER.

GRANT EXECUTE ON PZN_ADMIN.PROFILE_TAG_TYPE TO PZN_MB_USER;

 

3.       3. Define the array type reference to object PROFILE_TAG_TYPE.

CREATE TYPE PZN_ADMIN.PROFILE_TAG_ARRAY AS TABLE OF PZN_ADMIN.PROFILE_TAG_TYPE;

 

4.       4. Grant PROFILE_TAG_ARRAY execute access to PZN_MB_USER.

GRANT EXECUTE ON PZN_ADMIN.PROFILE_TAG_ARRAY TO PZN_MB_USER;

 

5.       5. Create store procedure package.

CREATE OR REPLACE

PACKAGE PZN_ADMIN.PZN_PROFILE_TAG_PKG

AS

PROCEDURE INSERT_PROFILE_TAG(

    PTA PROFILE_TAG_ARRAY);

END PZN_PROFILE_TAG_PKG;

 

6.       6. Create store procedure package body.

CREATE OR REPLACE

PACKAGE BODY PZN_ADMIN.PZN_PROFILE_TAG_PKG

AS

PROCEDURE INSERT_PROFILE_TAG(

    PTA PROFILE_TAG_ARRAY)

AS

BEGIN

 FOR I IN PTA.FIRST..PTA.LAST

 LOOP

    INSERT

    INTO PZN_ADMIN.PROFILE_TAG

      (

        PROFILE_TAG_ID,

        MID,

        TAG_ID,

        CUSTOMER_TYPE,

        SOURCE_SYSTEM,

        TAG_CREATED_DATE,

        INTEREST_LEVEL,

        SUPPRESSION_IND,

        SUPPRESSION_EXPIRY_DATE,

        LAST_HOUSEKEEPING_DATE,

        LAST_EVENT_DATE,

        REASON

      )

      VALUES

      (

        SEQ_PROFILE_TAG_ID.NEXTVAL ,

        PTA(I).MID,

        PTA(I).TAG_ID,

        PTA(I).CUSTOMER_TYPE,

        PTA(I).SOURCE_SYSTEM,

        TO_DATE(PTA(I).TAG_CREATED_DATE,'YYYY-MM-DD'),

        PTA(I).INTEREST_LEVEL,

        PTA(I).SUPPRESSION_IND,

        TO_DATE(PTA(I).SUPPRESSION_EXPIRY_DATE,'YYYY-MM-DD'),

        TO_DATE(PTA(I).LAST_HOUSEKEEPING_DATE,'YYYY-MM-DD'),

        TO_DATE(PTA(I).LAST_EVENT_DATE,'YYYY-MM-DD'),

        PTA(I).REASON

      );

 END LOOP;

END INSERT_PROFILE_TAG;

END PZN_PROFILE_TAG_PKG;

 

7.       7. Create synonym to PZN_MB_USER.

CREATE SYNONYM PZN_MB_USER.PZN_PROFILE_TAG_PKG FOR PZN_ADMIN.PZN_PROFILE_TAG_PKG;

 

8.       8. Grant execute access to PZN_MB_USER.

GRANT EXECUTE ON PZN_ADMIN.PZN_PROFILE_TAG_PKG TO PZN_MB_USER;

 

9.       9. Create the java class to call the procedure.

 

public class ProcedureTest2 {

 

        public static void insertProfileTag(){

                        Connection dbConn = null;

                        try {

                                        Object[] so1 = {"ee745b5782bfc311e0b5730a2aba15aa77",31,"C","eDB","2012-08-13",0,"0","2012-08-13","2012-08-13","2012-08-13","eDB"};

                                        Object[] so2 = {"ee745b5782bfc311e0b5730a2aba15aa77",32,"C","eDB","2012-08-13",0,"0","2012-08-13","2012-08-13","2012-08-13","eDB"};

                                        OracleCallableStatement callStatement = null;

                                        Class.forName("oracle.jdbc.driver.OracleDriver");

                                        dbConn = DriverManager.getConnection("jdbc:oracle:thin:@da957116.fmr.com:1521:orcl", "PZN_MB_USER", "PZN_MB_USER123");

                                       

                                        StructDescriptor st = new StructDescriptor("PZN_ADMIN.PROFILE_TAG_TYPE", dbConn);

                                        STRUCT s1 = new STRUCT(st, dbConn, so1);

                                        STRUCT s2 = new STRUCT(st, dbConn, so2);

                                        STRUCT[] deptArray = { s1, s2 };

                                       

                                        ArrayDescriptor arrayDept = ArrayDescriptor.createDescriptor("PZN_ADMIN.PROFILE_TAG_ARRAY", dbConn);

                                        ARRAY deptArrayObject = new ARRAY(arrayDept, dbConn, deptArray);

                                       

                                        callStatement = (OracleCallableStatement) dbConn.prepareCall("{call PZN_PROFILE_TAG_PKG.INSERT_PROFILE_TAG(?)}");

                                        callStatement.setArray(1, deptArrayObject);

                                        callStatement.executeUpdate();

                                        dbConn.commit();

                                        callStatement.close();

                        } catch (Exception e) {

                                        System.out.println(e.toString());

                                        e.printStackTrace();

                        }

        }

 

        public static void main(String[] args) {

                        insertProfileTag();

        }

}



銈炴矇榛樻槸閲戙倿 2012-08-13 16:17 鍙戣〃璇勮
]]>
Use LinkedHashMap to write one simple cachehttp://m.tkk7.com/dashi99/archive/2012/08/07/384989.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Tue, 07 Aug 2012 08:11:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/07/384989.htmlhttp://m.tkk7.com/dashi99/comments/384989.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/07/384989.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/384989.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384989.htmlThe processing costs for selecting a value from a database-table are fairly high compared to the costs having the value already in memory. So it seems preferrable to use some smart caching-mechanism that keeps often used values in your application instead of retrieving these values from resources somewhere ‘outside’.

Most frameworks have at least one cache implementation onboard, but there also exist several other implementations of caches like e.g. EHCache. Even ordinary HashMaps/Hashtables can serve as caches also.

A critial factor when using caches in Java is the size of the cache: when your cache grows too big, the Java Garbage Collector has to cleanup more often (which consumes time) or your application even crashes with a java.lang.OutOfMemoryError.

One way to control the memory-consumption of caches is to use SoftReferences in HashMaps/Hashtables, another one is to throw away old or unused content by implementing a caching-strategy like e.g. LRU.

A simple LRU-cache already ships within the components of the Java Standard Library: the LinkedHashMap. All you have to do is to tell your application whether the eldest entry in the map should be retained or removed after a new entry is inserted. Additionally a special constructor has to be used that defines the orderingMode for the map: ‘true’ for access-order (LRU), ‘false’ for insertion-order.

Suppose we want to cache a mapping of String-Names to String-Ids with a maximum size of 20480 entries.
How that can be done is shown by the example below with the use of an Anonymous Inner Class that overrides the removeEldestEntry-method of the LinkedHashMap.
import com.fmr.pzn.wmb.utils.Vaidator;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public final class SampleCache {

    private static final float LOAD_FACTOR = 0.75f;

    private static final int CACHE_MAX = 20480;

    private static final int CACHE_INIT = 10000;

    private static final LinkedHashMap<String, String> CACHE_MAP = new LinkedHashMap<String, String>(CACHE_INIT,
            LOAD_FACTOR, true) {

        private static final long serialVersionUID = 628057782352519437L;

        @Override
        protected boolean removeEldestEntry(Entry<String, String> eldest) {
            return size() > SampleCache.CACHE_MAX;
        }

    };


    private SampleCache() {
        super();
    }

    public static void putid(final String id, final String name) {
        if (isEmpty(id) || isEmpty(name)) {
            return;
        }

        CACHE_MAP.put(id, name);
    }

    public static String getByid(final String id) {
        return CACHE_MAP.get(id);
    }

    public static boolean isEmpty(final String field ){
        boolean isEmpty = false;
        if(field == null || field.isEmpty())
        {
            isEmpty = true;
        }
        return isEmpty;
    }
}
And based on the high performance environment, this cache will not thread safe. How to fix this small issue? we can use Collections.synchronizedMap() to synchronized cache. like:

    private static final Map<String, String> CACHE_MAP = Collections.synchronizedMap(new LinkedHashMap<String, String>(CACHE_INIT,
            LOAD_FACTOR, true) {

        private static final long serialVersionUID = 628057782352519437L;

        @Override
        protected boolean removeEldestEntry(Entry<String, String> eldest) {
            return size() > SampleCache.CACHE_MAX;
        }

    });

Now, there is one small cache exists in your application.

銈炴矇榛樻槸閲戙倿 2012-08-07 16:11 鍙戣〃璇勮
]]>
Part 13: java.util.concurrent - Atomic Variables http://m.tkk7.com/dashi99/archive/2012/08/06/384887.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 06 Aug 2012 02:50:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/06/384887.htmlhttp://m.tkk7.com/dashi99/comments/384887.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/06/384887.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/384887.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384887.html
In this article we will look into Atomic Variables which can help us to write lock free and wait free algorithms which were not possible prior to Java 5.0.

Two main points about Atomic Variables are 

   1. Help to write lock free and wait free algorithm

Under high contention ( lots of thread are fighting for lock ), JVM spends more time with scheduling of threads, managing contention, queues of waiting threads and less time in doing the real work.
This dramatically reduces the throughput of the process.
Problem with locking:
  1) Thread in block state cannot do anything else.
    2) If the blocked thread is high priority, then its a big disaster.
    3) Can cause Dead lock
    4) Managing a Block thread is a heavy weight process, so throughput decreases.

Soon we will see how can we write lock free algorithms using atomic variables


2. Implement very light weight process like CAS –


CAS (compares and swap):
       
Let’s take an example to understand the concept of CAS. Suppose we have once variable “i” and we are doing some calculation over “I” and storing the result back into “i”. In a nutshell-
        i = someComplicateComputation( i )
for “i” = 1,
        someComplicatedComputation(i) è 1234

In CAS Process following happens-
        A memory location V will be defined.
        A local variable A will be defined.
        A local variable B will be defined.

V will hold the initial value of “i”. So
        V = i =1
A = V = 1
B = result of that computation = 1234
compare ( V , A )
if
both values are same --> replace V with B's value.
else
        this means in the mean while someone has changed the value of V, so repeat the whole process again. Lets someone changes the value of “i”, hence V to 2.
       
             V = 2;
             A = V = 2
             B = result = 3246;
              compare ( V , A )
                        and so on...!!
       
This is very light weight process. This CAS technique is implemented by atomic package classes.



Example – Lets write a simple program which first increase the number by 1, then decrease the number by 1, and then increase again by 1. So overall effect is increase the number by 1. Lets run 4 threads concurrently access the method and compare the performance of AtomicInteger Vs Integer.
package com.jovialjava.blog.threads;

import java.util.concurrent.atomic.*;

public class AtomicVariableExample implements Runnable {
    AtomicInteger atomic_int_1 
= new AtomicInteger();
    AtomicInteger atomic_int_2 
= new AtomicInteger();
    
int int_1;
    
int int_2;
    
private static int count = 0;

    
public static void main(String[] args) {
        AtomicVariableExample pr 
= new AtomicVariableExample();
        
new Thread(pr).start();// 1 0 1
        new Thread(pr).start();// 2 1 2
        new Thread(pr).start(); // 3 2 3
        new Thread(pr).start(); // 4 3 4
        while (true) {
            
if (count == 4) {
                System.out.println(pr.atomic_int_1.get());
                System.out.println(pr.int_1);
                
break;
            }
        }

    }

    
public void run() {
        System.out.println(
"Inside run method");
        doCalc();

    }

    
private void doCalc() {
        
try {
            atomic_int_2 
= atomic_int_1;
            int_2 
= int_1;
            atomic_int_2.incrementAndGet();
            int_2 
= int_2 + 1;
            Thread.sleep(
1000);
            atomic_int_2.decrementAndGet();
            int_2 
= int_2 - 1;
            Thread.sleep(
1000);
            atomic_int_2.incrementAndGet();
            int_2 
= int_2 + 1;
            Thread.sleep(
1000);
            atomic_int_1 
= atomic_int_2;
            int_1 
= int_2;
            
synchronized (this) {
                count
++;
            }
        } 
catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


銈炴矇榛樻槸閲戙倿 2012-08-06 10:50 鍙戣〃璇勮
]]>
Part 12: java.util.concurrent : SingleThreadPool Example http://m.tkk7.com/dashi99/archive/2012/08/06/384886.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 06 Aug 2012 02:49:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/06/384886.htmlhttp://m.tkk7.com/dashi99/comments/384886.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/06/384886.html#Feedback1http://m.tkk7.com/dashi99/comments/commentRss/384886.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384886.html
This article will discuss about Thread pool that uses single thread to execute tasks. From Java 5.0+ one can get such pool from Executors using following method –
public static ExecutorService newSingleThreadExecutor()
    Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.



Example-
Suppose we have 100 properties files in an application. We have one thread that can read properties file and return a map value.

Pseudo code – READER THREAD

Config Reader implements Callable<Map<String, String>
try{
    // Get the file name in the constructor of thread
    // Check if File exists
    // Read the file and retrun the map object
}catch(Exception e){
        //release all the resource
        //return null
}

Main THREAD-
        // Get a Single thread pool from Executors
 try{
    // Get the list of all properties file in the directory
    // Create a READER THREAD by passing the name of file
    // store the READER thread in the a list
    //release all the thread in one go and get the Map objects
}catch(Exception e){
                //release all the resources
                // print the stack trace
}finally{
        //shutdown the thread pool
}
package com.jovialjava.blog.threads;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class SingleReader implements Callable<Properties> {

    
private String name = null;

    
public SingleReader(String name) {
        
this.name = name;
    }

    
public Properties call() {
        
try {
            File f 
= new File(name);
            Properties prop 
= new Properties();
            
if (f.exists() && f.canRead() && f.isFile()) {
                FileInputStream in 
= new FileInputStream(f);
                prop.load(in);
                
return prop;
            } 
else {
                System.err.println(
"Please check about this file:[" + f.getAbsolutePath() + "]");
                
return null;
            }
        } 
catch (Exception e) {
            e.printStackTrace();
            
return null;
        }
    }
}

public class SingleThreadPoolExample {
    
public static String directory = "config";
    
private static ExecutorService executorPool = null;

    
public static void main(String args) {
        
try {
            File dir 
= new File(directory);
            
if (dir.isDirectory()) {
                List
<Callable<Properties>> fileList = new ArrayList<Callable<Properties>>();
                String[] files 
= dir.list();
                
/**
                 * Optimization - Single thread executor.
                 
*/
                executorPool 
= Executors.newSingleThreadExecutor();

                
for (String file : files) {
                    Callable
<Properties> reader = new SingleReader(dir.getAbsolutePath() + File.separator + file);
                    fileList.add(reader);
                }
                List
<Future<Properties>> results = executorPool.invokeAll(fileList);
                
/**
                 * Check how many success and how many failure
                 
*/
                
int success = 0, failure = 0;
                
for (Future<Properties> result : results) {
                    
if (result.get() == null) {
                        failure
++;
                    } 
else {
                        success
++;
                    }
                }
                System.out.println(
"Total number of files [" + fileList.size() + "]");
                System.out.println(
"Success Count [" + success + "]");
                System.out.println(
"Failure Count [" + failure + "]");
            } 
else {
                
throw new IllegalArgumentException("There is no such directory name -" + directory);
            }
        } 
catch (Exception e) {
            e.printStackTrace();
        } 
finally {
            
if (executorPool != null) {
                executorPool.shutdown();
            }
        }
    }

}


銈炴矇榛樻槸閲戙倿 2012-08-06 10:49 鍙戣〃璇勮
]]>
Part 11: java.util.concurrent - CachedThreadPool Examplehttp://m.tkk7.com/dashi99/archive/2012/08/06/384885.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 06 Aug 2012 02:47:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/06/384885.htmlhttp://m.tkk7.com/dashi99/comments/384885.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/06/384885.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/384885.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384885.html
This article will discuss about Thread pool that can reuse previously constructed threads when they are available. From Java 5.0+ one can get such pool from Executors using following method –
public static ExecutorService newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.


Example-
Suppose we have 100 properties files in an application. We have one thread that can read properties file and return a map value. We want to optimize the time to read all 100 properties file by using concurrent reading. Here optimize means – we need a perfect balance between CPU Utilization and total time consumed by reading process.

Pseudo code – READER THREAD

Config Reader implements Callable<Map<String, String>
try{
    // Get the file name in the constructor of thread
    // Check if File exists
    // Read the file and retrun the map object
}catch(Exception e){
        //release all the resource
        //return null
}

Main THREAD-
        // Get a Cached thread pool from Executors
 try{
    // Get the list of all properties file in the directory
    // Create a READER THREAD by passing the name of file
    // store the READER thread in the a list
    //release all the thread in one go and get the Map objects
}catch(Exception e){
                //release all the resources
                // print the stack trace
}finally{
        //shutdown the thread pool
}
package com.jovialjava.blog.threads;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class CachedReader implements Callable<Properties> {

    
private String name = null;

    
public CachedReader(String name) {
        
this.name = name;
    }

    
public Properties call() {
        
try {
            File f 
= new File(name);
            Properties prop 
= new Properties();
            
if (f.exists() && f.canRead() && f.isFile()) {
                FileInputStream in 
= new FileInputStream(f);
                prop.load(in);
                
return prop;
            } 
else {
                System.err.println(
"Please check about this file:[" + f.getAbsolutePath() + "]");
                
return null;
            }
        } 
catch (Exception e) {
            e.printStackTrace();
            
return null;
        }
    }
}

public class CachedThreadPoolExample {
    
public static String directory = "config";
    
private static ExecutorService executorPool = null;
    
private static int MAX_THREADS = 20;

    
public static void main(String args) {
        
try {
            File dir 
= new File(directory);
            
if (dir.isDirectory()) {
                List
<Callable<Properties>> fileList = new ArrayList<Callable<Properties>>();
                String[] files 
= dir.list();
                
/**
                 * Optimization - Reuse the the threads.
                 
*/
                executorPool 
= Executors.newCachedThreadPool();

                
for (String file : files) {
                    Callable
<Properties> reader = new CachedReader(dir.getAbsolutePath() + File.separator + file);
                    fileList.add(reader);
                }
                List
<Future<Properties>> results = executorPool.invokeAll(fileList);
                
/**
                 * Check how many success and how many failure
                 
*/
                
int success = 0, failure = 0;
                
for (Future<Properties> result : results) {
                    
if (result.get() == null) {
                        failure
++;
                    } 
else {
                        success
++;
                    }
                }
                System.out.println(
"Total number of files [" + fileList.size() + "]");
                System.out.println(
"Success Count [" + success + "]");
                System.out.println(
"Failure Count [" + failure + "]");
            } 
else {
                
throw new IllegalArgumentException("There is no such directory name -" + directory);
            }
        } 
catch (Exception e) {
            e.printStackTrace();
        } 
finally {
            
if (executorPool != null) {
                executorPool.shutdown();
            }
        }
    }
}


銈炴矇榛樻槸閲戙倿 2012-08-06 10:47 鍙戣〃璇勮
]]>
Part 10: java.util.concurrent - ScheduledThreadPool Example http://m.tkk7.com/dashi99/archive/2012/08/06/384884.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 06 Aug 2012 02:45:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/06/384884.htmlhttp://m.tkk7.com/dashi99/comments/384884.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/06/384884.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/384884.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384884.html
This article will discuss about Thread pool that can schedule threads to run after a specified interval of time. From Java 5.0+ one can get such pool from Executors using following method –

public static ScheduledExecutorService 
       newScheduledThreadPool(int corePoolSize)
    Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

The return type of this method (return type of thread pool) is ScheduledExecutorService.Some of the salient features of ScheduledExecutorService are –
  1.         Schedule a Callable or Runnable to run once with a fixed delay after submission
  2.         Schedule a Runnable to run periodically at a fixed rate
  3.         Schedule a Runnable to run periodically with a fixed delay between executions
  4.         Submission returns a ScheduledFutureTask handle which can be used to cancel the task
  5.  .Like Timer, but supports pooling


Example:
  1. Suppose we are building a Bank check processing system. Here is the process –
  2.  Every local branch collect cheques and create a txt file contain cheque info.
  3.  A service runs which copy the cheque txt file from local branch to main server.
  4.  A Local service runs on server which check if any file has received and notify the cheque Clearing process.


We will try to make “Local Service”, which check the file reception and “Copying process” Which copy file from client machine to Server.
Pseudo Code-

//Define Local & Copying service running interval time in Seconds
//Make an ScheduledThreadPool with pool size 2
try{
    // Make Local Service thread
    // Make Copying process thread
    // Scheduled Both thread to run at regular interval
}catch(Exception e){
 //release all resources
}

LocalService Thread-
Try{
        //Check if directory exists
        //Check if any file exists in directory
        //return status
}catch(Exception e){
        //Print necessary exception
}

Copying Process Thread-
Try{
   // Check if File existin on remote server
   // Copy the file to main server
}catch(Exception e){
        //Print necessary exception
}
package com.jovialjava.blog.threads;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

//LOCAL SERVICE THREAD
class LocalService implements Runnable {

    
private String DIRECTORY = null;

    
public LocalService(String DIRECTORY) {
        
this.DIRECTORY = DIRECTORY;
    }

    
public void run() {
        
try {
            File dir 
= new File(this.DIRECTORY);
            
if (dir.isDirectory()) {
                
if (dir.list().length > 0) {
                    System.out.println(
"FILE EXISTS");
                }
            } 
else {
                System.err.println(
"NO SUCH DIRECTORY [" + dir.getAbsolutePath() + "] exists");
            }
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// COPYING SERVICE THREAD
class CopyService implements Runnable {

    
private String REMOTE_DIR = null;
    
private String LOCAL_DIR = null;

    
public CopyService(String remoteDir, String localDir) {
        
this.REMOTE_DIR = remoteDir;
        
this.LOCAL_DIR = localDir;
    }

    
public void run() {
        
try {
            File remote 
= new File(this.REMOTE_DIR);
            File local 
= new File(this.LOCAL_DIR);
            
if (remote.isDirectory() && local.isDirectory()) {
                
if (remote.list().length > 0) {
                    System.out.println(
"REMOTE FILE FOUND, COPYING");
                    
// --- Call the file copying method.
                } else {
                    System.out.println(
"NO REMOTE FILE FOUND");
                }
            } 
else {
                System.err.println(
"PLEASE CHECK DIRECTORY [" + remote.getAbsolutePath() + " OR/AND"
                        
+ local.getAbsolutePath() + "] existence");
            }
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class ScheduledExample {

    
private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    
private static final int LOCAL_INTERVAL = 5, COPY_INTERVAL = 2;
    
private static final String REMOTE_DIR = "REMOTE", LOCAL_DIR = "LOCAL";

    
public static void main(String args) {
        Runnable localService 
= new LocalService(LOCAL_DIR);
        Runnable remoteService 
= new CopyService(REMOTE_DIR, LOCAL_DIR);
        
try {
            executor.scheduleWithFixedDelay(localService, 
0, LOCAL_INTERVAL, TimeUnit.SECONDS);
            executor.scheduleWithFixedDelay(remoteService, 
0, COPY_INTERVAL, TimeUnit.SECONDS);
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }
}


銈炴矇榛樻槸閲戙倿 2012-08-06 10:45 鍙戣〃璇勮
]]>
Part 9: java.util.concurrent : FixedThreadPool Example http://m.tkk7.com/dashi99/archive/2012/08/06/384882.html銈炴矇榛樻槸閲戙倿銈炴矇榛樻槸閲戙倿Mon, 06 Aug 2012 02:43:00 GMThttp://m.tkk7.com/dashi99/archive/2012/08/06/384882.htmlhttp://m.tkk7.com/dashi99/comments/384882.htmlhttp://m.tkk7.com/dashi99/archive/2012/08/06/384882.html#Feedback0http://m.tkk7.com/dashi99/comments/commentRss/384882.htmlhttp://m.tkk7.com/dashi99/services/trackbacks/384882.html
This article will discuss about Thread pool with fixed number of thread. From Java 5.0+ one can get such pool from Executors using following method –
public static ExecutorService 
               newFixedThreadPool(int nThreads)
    Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

Example-
Suppose we have 100 properties files in an application. We have one thread that can read properties file and return a map value. We want to optimize the time to read all 10 properties file by using concurrent reading. Here optimize means – we need a perfect balance between CPU Utilization and total time consumed by reading process.

Pseudo code – READER THREAD

Config Reader implements Callable<Map<String, String>
try{
    // Get the file name in the constructor of thread
    // Check if File exists
    // Read the file and retrun the map object
}catch(Exception e){
        //release all the resource
        //return null
}

Main THREAD-
        // Get a fixed thread pool from Executors
 try{
    // Get the list of all properties file in the directory
    // Create a READER THREAD by passing the name of file
    // store the READER thread in the a list
    //release all the thread in one go and get the Map objects
}catch(Exception e){
                //release all the resources
                // print the stack trace
}finally{
        //shutdown the thread pool
}
package com.jovialjava.blog.threads;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class Reader implements Callable<Properties> {

    
private String name = null;

    
public Reader(String name) {
        
this.name = name;
    }

    
public Properties call() {
        
try {
            File f 
= new File(name);
            Properties prop 
= new Properties();
            
if (f.exists() && f.canRead() && f.isFile()) {
                FileInputStream in 
= new FileInputStream(f);
                prop.load(in);
                
return prop;
            } 
else {
                System.err.println(
"Please check about this file:[" + f.getAbsolutePath() + "]");
                
return null;
            }
        } 
catch (Exception e) {
            e.printStackTrace();
            
return null;
        }
    }
}

public class FixedThreadPoolExample {
    
public static String directory = "config";
    
private static ExecutorService executorPool = null;

    
public static void main(String args) {
        
try {
            File dir 
= new File(directory);
            
if (dir.isDirectory()) {
                List
<Callable<Properties>> fileList = new ArrayList<Callable<Properties>>();
                String[] files 
= dir.list();
                
/**
                 * Optimization - just 20% of number of files.
                 
*/
                executorPool 
= Executors.newFixedThreadPool(files.length / 5);

                
for (String file : files) {
                    Callable
<Properties> reader = new Reader(dir.getAbsolutePath() + File.separator + file);
                    fileList.add(reader);
                }
                List
<Future<Properties>> results = executorPool.invokeAll(fileList);
                
/**
                 * Check how many success and how many failure
                 
*/
                
int success = 0, failure = 0;
                
for (Future<Properties> result : results) {
                    
if (result.get() == null) {
                        failure
++;
                    } 
else {
                        success
++;
                    }
                }
                System.out.println(
"Total number of files [" + fileList.size() + "]");
                System.out.println(
"Success Count [" + success + "]");
                System.out.println(
"Failure Count [" + failure + "]");
            } 
else {
                
throw new IllegalArgumentException("There is no such directory name -" + directory);
            }
        } 
catch (Exception e) {
            e.printStackTrace();
        } 
finally {
            
if (executorPool != null) {
                executorPool.shutdown();
            }
        }
    }
}


銈炴矇榛樻槸閲戙倿 2012-08-06 10:43 鍙戣〃璇勮
]]>
主站蜘蛛池模板: 麻豆最新国产剧情AV原创免费| 自怕偷自怕亚洲精品| 99re热免费精品视频观看| 久久九九免费高清视频| 男人天堂2018亚洲男人天堂| 亚洲AV日韩AV永久无码免下载| 日日AV拍夜夜添久久免费| 91在线老王精品免费播放| 99精品全国免费观看视频..| 国产亚洲美女精品久久| 亚洲欧美自偷自拍另类视| 亚洲日本国产乱码va在线观看| 亚洲gv猛男gv无码男同短文| 国产精品无码一区二区三区免费| 青青青免费国产在线视频小草| 一级毛片不卡片免费观看| 久久久精品午夜免费不卡| 国产乱妇高清无乱码免费| 边摸边吃奶边做爽免费视频网站 | 亚洲伊人久久大香线蕉啊| 亚洲乱码精品久久久久..| 亚洲中文字幕无码爆乳av中文| 日韩免费高清视频| 大地资源免费更新在线播放| 999国内精品永久免费视频| 99热在线免费观看| 久久精品免费电影| 日本一区二区免费看| 国产午夜无码精品免费看动漫| 中文字幕无码免费久久9一区9 | 亚洲日本一区二区一本一道| 免费a级毛片网站| 免费不卡中文字幕在线| 免费一级毛片免费播放| 亚洲av成人一区二区三区在线观看| 日韩免费无码一区二区视频| 永久黄网站色视频免费直播| 国产精品自在自线免费观看| 免费jlzzjlzz在线播放视频| 亚洲AV无码一区二区三区在线观看 | 亚洲一级毛片免费观看|