Multiple newSingleThreadExecutor vs newFixedThreadPool from ExecutorService

In my application, I have 4 different processes that work constantly with small pauses.

The current version of the code runs each process in a separate thread from the old school:

Thread nlpAnalyzer = new Thread(() -> { // infine lop for auto restore in case of crash //noinspection InfiniteLoopStatement while (true) { try { // this method should run permanently, pauses implemented internally NLPAnalyzer.analyzeNLP(dbCollection); } catch (Exception e) { e.printStackTrace(); } } }); nlpAnalyzer.setName("im_nlpAnalyzer"); nlpAnalyzer.start(); 

Now I would like to reorganize this code using ExecutorService . To do this, I can use at least two approaches:

  • newFixedThreadPool(numOfProc) ;
  • numOfProc * newSingleThreadExecutor() .

My questions:

  • Is there a reason why I should prefer one option over another?
  • What is more appropriate for creating a thread pool with X threads or generating X newSingleThreadExecutor?
  • Pro et contra of each approach?
+5
source share
2 answers

Given that each task is an infinite loop, I would use

 newCachedThreadPool(); 

This will create a thread for each task that it needs (and no more)

The advantage of using a single pool with multiple pools is that you can disable the pool individually or give each thread a name, but if you don't need it, it's just an overhead.

Note. You can change the name of the stream using setName ("My task"), which may be useful for debugging / profiling purposes.

One way to use the ExecutorService is that it catches any uncaught exceptions / errors and places them in the returned Future object. Often this Future discarded, which means that if your task dies unexpectedly, it can also do it quietly.

I suggest you try / catch (Throwable) outside the loop and register it so you can see when the thread ever unexpectedly dies. e.g. OutOfMemoryError

+3
source

I do not see any benefit to the parameter below, except to disable a single artist.

 numOfProc * newSingleThreadExecutor() 

But you have more options. I prefer one of the three options from Executors .

 newFixedThreadPool newCachedThreadPool newWorkStealingPool 

See SE questions below for relevant queries:

Java plug / join to ExecutorService - when to use which?

How to use Java Executor?

Difference between Executors.newFixedThreadPool (1) and Executors.newSingleThreadExecutor ()

+1
source

Source: https://habr.com/ru/post/1246389/


All Articles