Home > Software design >  ExecutorService with single thread in Java Multithreading
ExecutorService with single thread in Java Multithreading

Time:09-05

What is the point of creating ExecutorService with single thread in java multithreading means why not to create single separate thread instead of ExecutorService with a single thread?

Which is preferable in which case?

CodePudding user response:

What is the point of creating ExecutorService with single thread?

Sometimes you have an application that generates a number of tasks that may be performed concurrently with the rest of the program, but which must not be performed concurrently with each other. I like to tell students, "If you want your program to do things in a certain order, the best way to achieve that is to have the program do all of those things in a single thread." So, If you want the program to perform a sequence of "background" tasks in a certain order, a single-threaded executor may be just what you need.

why not to create single separate thread?

Because if all you do is instantiate a new Thread(...), that doesn't give you the ability to submit tasks to it. If you want to be able to ask that thread to perform different tasks, then you'd have to write the code that allows it to happen, and when you're done writing that code, you have effectively re-invented an executor service.

A single-threaded executor service creates a single separate thread, and then it does other stuff. The "other stuff" adds value.

  • Related