Java: single-threaded sub-Artist as part of another multi-threaded Artist

I would like to accomplish some tasks in a serialized way. A typical solution for this is to create

Executor executor = Executors.newSingleThreadedExecutor();

and run tasks on it.

However, I already have a thread pool that is multithreaded.

Is there a simple way to get a sub-executor that behaves as a single-threaded (like in: runs only one task at a time), but uses another (possibly not single-threaded) executor as a “backend” instead of creating a completely new OS thread?

There are several use cases for why we would like to do this:

  • an application may already have a thread pool, for example. background tasks, with a given priority, etc. that we would like to reuse.
  • Similarly, we can pass to Executor, which is not just a pool of threads (for example, delaying execution for subsequent measurement of runtime, etc.),
    • a subset of which is passed to MoreExecutors.directExecutor () for testing (so, for example, Futures is resolved immediately).

EDIT : added above examples

+2
source share
2 answers

Such a zero-threaded operator is called SerialExecutorand described in the java documentation before java.util.concurrent.Executor. However, it has a slight flaw: for each sent one, Runnableit creates a wrapper object. My own implementation does not create additional objects.

+2
source

: .

: ... .

: "" ... ? ; , , , - ?

- , "" "" ? ?

, ; , ... : ?

, , ; ; - , :

Executor executor = Executors.newSingleThreadedExecutor();

/: , ; . Actor (, , ) - . ; , ... , ; , .

0

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


All Articles