Does Java provide an executorservice that allows workers to execute on the same thread?

I am looking for an implementation of executorservice that will provide the following semantics Each thread is occupied by a "worker" who performs certain tasks according to input Each worker is guaranteed to execute in only one thread, so it should be allowed to maintain state between tasks without synchronization overhead, because it will synchronize with itself in one thread

Therefore, assuming that I have 100 inputs and 10 workers, I hope to write the following:

for (Input input: inputs) {
    // The following code would pass t to all 10 workers,// each bound to their own thread,// and wait for them to complete.
    executor.invokeAll(input);
}

Note that each worker does different things for any given input Input is not a runnable code block, it is just a worker's parameter Each staff member decides how to handle the input However, to make it simpler, the staff implemented an interface that allows it to be called in a polymorphic manner to receive input

I used map < < worker, workerexecution >, and attacked some effective things together. Among them, workerexecution is my work in executors The thin wrapper around newsinglethreadpool, and only one worker instance is running in each thread pool I'd rather find someone who knows what they're doing to write: -)

Potential shortcomings I'm fine

I realize that this semantics can lead to inefficiency, but it's not easy for me to try to maximize the benefit of development time, and redesign every implementation of worker is thread safe I mean, inefficiency is that the execution may / looks like this (simulate up to 2 active threads in this example):

| Task 1    | Task 2    | Task 3    | Task 4    |
Worker 1 | =@        | =@        | =@        | =@        |
Worker 2 | ==@       | ==@       | ==@       | ==@       |
Worker 3 |   ==@     |   ==@     |   ==@     |   ==@     |
Worker 4 |    =====@ |    =====@ |    =====@ |    =====@ |

The problem is that after worker 3 is finished, there are no tasks left to do until worker 4 is finished This may be any long time that the CPU can be idle

Does such executorservice exist?

Solution

It sounds like what you really want is actors In short, an actor is an object running in a thread. It has a "mailbox" of tasks, which is responsible for processing in order Akka seems to be the leading library / framework currently providing actors on the JVM Look over there And another so answer lists alternatives to several actors in Java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>