1

For example, I execute runnable block via ExecutorService instance and that runnable block execute some asynchronous code via the same ExecutorService instance. So my code looks like:

final ExecutorService eService = Executors.newFixedThreadPool(nThreads);
    eService.execute(new Runnable() {
        public void run() {
            eService.execute(new Runnable() {
                public void run() {
                    System.out.println("Successfully created");
                }
            });
        }
    });
  1. Is this code thread safe, because ExecutorService doesn't have a state?

In my real app I have some threads that created new threads inside them and I want to use one ExecutorService instance(maybe a bad practice?) with configurable thread pool size.

  1. Is it a bad practice to do have one ExecutorService instance for different threads?
  2. And if yes, maybe there are some alternatives?
1
  • For the record, ExecutorService certainly has state. It's just thread-safe so multiple threads (even those that are running in its own pool) can submit jobs to it. Commented Sep 7, 2021 at 21:42

1 Answer 1

3

It look fine. It is a good practice to reuse threads instead of spawning new ones (which is expensive) and one of possible implementations of such thread sharing can be usage of ExecutorService

Just keep in mind, that it will work for the code you have mentioned, It might break if you will try to await for the result of scheduled operation. This can lead to obvious deadlock when all the threads (from the pool) will be waiting for the result of the operation that awaits a free thread (in that pool) to execute it.

Sign up to request clarification or add additional context in comments.

3 Comments

And is it okay to share the one ExecutorService instance among other Runnable classes via constructor parameter or is it better to have singleton class of ExecturService wrapper?
And again - it depends. Once you might want to have general purpose threadpool and is used for everything (then singleton), other time you will like to to use dedicated thread pool for some specific task only (then pass as arg).
Just to expand a bit on the last paragraph: If you already know there are new jobs coming out of jobs executed in executor1, it is a good idea to execute those new jobs in another executor2. And so on. Just to be sure there are no deadlocks hidden in your jobs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.