简体   繁体   中英

Parallelization (Java 8) vs Concurrency (Java 7)

I want to parse multiple files to extract the required data and then write the output into an XML file. I have used Callable Interface to implement this. My colleague asked me to use Java 8 feature which does this job easily. I am really confused which one of them I should use now.

list.parallelStream().forEach(a -> {
            System.out.println(a);
        });

Using concurrency or a parallel stream only helps if you have independent tasks to work on. A good example of when you wouldn't do this is what you are locking on a shared resources eg

// makes no sense to use parallel here.
list.parallelStream().forEach(a -> {
        // locks System.out so only one thread at a time can do any work.
        System.out.println(a);
    });

However, as a general question, I would use parallelStream for processing data, instead of the concurrency libraries directly because;

  • a functional style of coding discourages shared mutable state. (Actually how are not supposed to have an mutable state in functional programming but Java is not really a functional language)
  • it's easier to write and understand for processing data.
  • it's easier to test whether using parallel helps or not. Most likely ti won't and you can just as easily change it back to being serial.

IMHO Given the chances that using parallel coding will really help is low, the best feature of parallelStream is not how simple it is to add, but how simple it is to take out.

The concurrency library is better if you have ad hoc work which is difficult to model as a stream of data. eg a worker pool for client requests might be simplier to implement using an ExecutorService.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM