ForkJoinPool to use multi-threaded split task, perform the task, the result of the merger.

ForkJoinPool is jdk1.7 written by Doug Lea implementation recursive call task split, merge, thread pool.

Code Example:

Package www.itbac.com; 

Import com.alibaba.fastjson.JSONObject;
 Import org.springframework.beans.factory.annotation.Autowired;
 Import org.springframework.stereotype.Service;
 Import org.springframework.web.client.RestTemplate; 

Import java.util.ArrayList;
 Import . java.util.concurrent * ; 

/ ** 
 * parallel Interface http call 
 * / 
@Service 
public  class UserServiceForkJoin {
     // essentially a thread pool, the default number of threads: number of CPU cores of 
    ForkJoinPool forkJoinPool = new new ForkJoinPool (10 , ForkJoinPool.defaultForkJoinWorkerThreadFactory,
            null , to true ); 
    @Autowired 
    Private RestTemplate RestTemplate; 

    / ** 
     * query data from multiple systems, combined returned 
     * / 
    public Object getUserInfo (String the userId) throws ExecutionException, InterruptedException {
         // another example, the plurality of check table data of the database , in multiple query
         // the fork / the Join
         // forkJoinPool.submit () 
        the ArrayList <String> URLs = new new the ArrayList <> (); 
        urls.add ( "http://www.itbac.com/userinfo-api/get ? userId = "+ userId); 
        urls.add ( " http://www.itbac.com/integral-api/get?userId= "+ userId);

        HttpJsonRequest httpJsonRequest = new HttpJsonRequest(restTemplate, urls, 0, urls.size() - 1);
        ForkJoinTask<JSONObject> forkJoinTask = forkJoinPool.submit(httpJsonRequest);

        JSONObject result = forkJoinTask.get();
        return result;
    }
}

// 自定义任务类, 继承递归任务。
class HttpJsonRequest extends RecursiveTask<JSONObject> {

    RestTemplate restTemplate;
    ArrayList<String> urls;
    int start;
    int end;

    HttpJsonRequest (RestTemplate RestTemplate, the ArrayList <String> URLs, int Start, int End) {
         the this .restTemplate = RestTemplate;
         the this .urls = URLs;
         the this .start = Start;
         the this .end = End; 
    } 

    // is performed to actually a method entry (task splitting) 
    @Override
     protected the JSONObject Compute () {
         int COUNT = End - Start; // represents the current task that requires many data processing
         @ themselves according to the service to judge whether the scene is large task, whether split 
        IF (COUNT == 0 ) {
            Url String = urls.get (Start);
             // TODO if only one interface calls, immediately call the 
            Long userinfoTime = System.currentTimeMillis (); 
            String the Response = restTemplate.getForObject (url, String. Class ); 
            JSONObject value = JSONObject.parseObject (Response); 
            System.out.println (Thread.currentThread () + "interface call finished" + (System.currentTimeMillis () - userinfoTime) + "#" + URL);
             return value; 
        } the else { // if multiple an interface calls, split into subtasks 7,8, 9,10
            System.out.println (Thread.currentThread () + "task split time" );
             // median formation. 
            int X = (Start + End) / 2 ;
             // tasks from the beginning, to an intermediate value. 
            HttpJsonRequest = HttpJsonRequest new new HttpJsonRequest (RestTemplate, urls, Start, the X-); // responsible for which part?
             // fork split task. 
            httpJsonRequest.fork ();
             // tasks from the intermediate value of +1, to the end. 
            HttpJsonRequest1 = HttpJsonRequest new new HttpJsonRequest (RestTemplate, urls, the X-+ 1, End); // responsible for which part of the deal? 
            HttpJsonRequest1.fork (); 

            // get treatment results join 
            JSONObject the Result = new new JSONObject ();
            
            //join合并结果。
            result.putAll(httpJsonRequest.join());
            result.putAll(httpJsonRequest1.join());
            
            return result;
        }
    }
}

The task is to split the thread pool to execute, and then merge. And capture the return value Future somewhat similar. Just do a task split abstract package.

 

Features:

ThreadPoolExecutor only the thread pool maintains a queue. Multi-threading to compete for task queue to execute.

 

The ForkJoinPool every big task is to maintain a queue, fork out a small task is split in their queue. A thread to handle their own tasks in the queue at this time, no thread competition, efficiency is higher than the thread pool.

The current thread to its own queue process is over, go and compete for other threads to handle other tasks queue, this term is called work stealing.

 

ForkJoinPool maintains multiple queues, ThreadPoolExecutor only maintains a queue of threads to reduce competition through multiple queues, thereby improving efficiency.

Guess you like

Origin www.cnblogs.com/itbac/p/11297013.html