How is the multi-user segment of code with intensive computation in Java?

I have a Java program, its part is calculated intensively, for example

for i = 1 :512
   COMPUTE INTENSIVE SECTION
end

I want to break it into multithreading, make it faster at startup.

COMPUTER INTENSIVE SECTION is not sequential. This means that at first I = 1 or I = 5 fists ...

Can anyone give me a great guide on this. How to do it? Thank you so much! Happy Thanksgiving!

+5
source share
5 answers

It looks like the thread pool will be good. Basically, you whip a collection of N different threads, and then query them in a loop. The request is blocked until the stream is available.

ThreadPool pool = Executors.newFixedThreadPool(10); // 10 threads in the pool
ArrayList<Callable> collectionOfCallables = new ArrayList<Callable>( );
for (...) {
  Callable callable = new Callable<Foo>() { public Foo call() { COMPUTE INTENSIVE SECTION } }
  collectionOfCallables.add(callable);
}

ArrayList<Future<Foo>> results = pool.invokeAll( collectionOfCallables );

pool.awaitTermination(5, TimeUnit.MINUTES ); // blocks till everything is done or 5 minutes have passed.

. get() , ( ).

+3

Concurrency Trail Java. .

, ( Executor) factory Executors class Runnable :

for(int i = 0; i < 512; i++){
    executor.execute(new Runnable(){public void run(){
        // your heavy code goes here
    }});
}
+5

, :

ExecutorService es = Executors.newCachedThreadPool();
for(int i = 0; i < 512; i++){
    es.execute(() -> {
        // code goes here
    });
}
0

, ForkJoinPool .

8 core CPU, 8

ForkJoinPool forkJoinPool = new ForkJoinPool(8); 

Executor Service FixedThreadPool, Callable,

ExecutorService executorService = Executors.newFixedThreadPool(8);

Future future = executorService.submit(new Runnable() {
public void run() {
    System.out.println("Your compute intensive task");
}
});

future.get();  //returns null if the task has finished correctly.

There is one advantage with ForkJoinPool. Idle threads will steal jobs from busy threads from the blokcingQueue where your tasks were sent Runnable/Callable.

Java 8 added another new API in Executors: newWorkStealingPool

If you need to wait for the completion of all tasks, use invokeAll()for ExecutorService.

Take a look at the article on BenjaminAdvanced Parallel APIs Using Java 8

0
source

All Articles