Using Callable in java sequentially executes the code

4

I'm doing a server in java that wanted to perform certain tasks in parallel. I have a list of a certain type I want 20 threads to deal with deterimented list elements.

for( Item item : result ) {
    Callable< List< IResult > > callable = new HTMLParser( item ); 
    Future< List< IResult > > future = pool.submit( callable );
    set.add( future );
}

for( Future< List< IResult > >  future : set ) {
    List< IResult > result = future.get( ); // wait for a processor to complete
    if( result != null && !result.isEmpty( ) )
        FResults.addAll( result ); 
    }
}

But by running this solution, analyzing the logs it seems to me that it is running the threads sequentially

2016-12-06 14:17:02.106 DEBUG 18229 --- [pool-1-thread-5] ......
2016-12-06 14:17:02.106 DEBUG 18229 --- [pool-1-thread-5] ....
2016-12-06 14:17:02.106 DEBUG 18229 --- [pool-1-thread-5] .....
2016-12-06 14:17:02.106 DEBUG 18229 --- [pool-1-thread-5] .......
2016-12-06 14:17:02.106  INFO 18229 --- [pool-1-thread-5] .....
2016-12-06 14:17:02.243 DEBUG 18229 --- [ool-1-thread-19] .....
2016-12-06 14:17:02.243  INFO 18229 --- [ool-1-thread-19] ....
2016-12-06 14:17:02.587 DEBUG 18229 --- [ool-1-thread-16] .....
2016-12-06 14:17:02.587 DEBUG 18229 --- [ool-1-thread-16] ....
2016-12-06 14:17:02.587 DEBUG 18229 --- [ool-1-thread-16] .....
2016-12-06 14:17:02.587 DEBUG 18229 --- [ool-1-thread-16] .....
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] .....
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] ......
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] .....
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] ....
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] ......
2016-12-06 14:17:02.588 DEBUG 18229 --- [ool-1-thread-16] ...

The uam thread logs appear sequentially all followed, does not make sense to me. Any ideas?

    
asked by anonymous 06.12.2016 / 16:03

1 answer

3

In fact, it makes perfect sense:

List< IResult > result = future.get( ); // wait for a processor to complete

You are calling get on every Future , which is blocking, thus doing a sequential execution since the next get will only be called when the current finishes executing.

The Future s API gives you the isDone , which is not blocking and will return true if that computation is complete.

Instead of passing% s to% s, you can use invokeAll :

List<Future<Whatever>> futures = pool.invokeAll(callables);

Then iterate over futures by calling Callable when you know it has completed processing:

for(Future<List<Whatever>> f : futures) {
    if(f.isDone()) {
        f.get() // aqui você faz a mágica acontecer
    }
}

Finally, you do not need to get stuck in the loop that checks get , you can periodically check the result.

    
06.12.2016 / 16:44