I am developing some code that will eventually be multithreaded, using a thread pool Executor
. The tasks executed by the thread pool will make call-backs and (sometimes) submit further tasks to the task queue. I would like to develop the code single threaded first, get it right (I'm using Test Driven Development) and only then make the alterations to ensure thread safety (locks, etc). To do that, I need an Executor
that is safe to use with non thread-safe code.
I think that means I need an Executor
that is single-threaded. That is, it is causes all work to be done by the calling thread. Does the JRE provide such an Executor
? Or is it possible to configure one of its Executor
s to operate in that mode?
I am already using the Humble Object testing pattern to test most of my code single-threaded. However, some of my code must interact with an Executor
, or perhaps an ExecutorService
, because it is about scheduling and resubmission of tasks, and it will do so in a non-trivial manner. Testing that code is the challenge here. The tasks update a shared object, which holds their results and input data. I want to delay having to make that shared object thread-safe until I have the scheduling and resubmission code implemented and debugged.
If you plan to develop a single thread solution first than abstracting your business logic away from Thread
semantics is the way to go. Implement a Callable
or Runnable
that you can test without starting a new Thread
e.g. by using a mocked Executor
in your unit tests.
If the code really needs only an Executor
, and not a (much more complex) ExecutorService
, it is easy to implement your own single-threaded executor that does precisely what is needed. The API documentation of Executor
even shows you how to do so:
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
If the code does need an ExecutorService
, it is possible that the single thread executor provided byExecutors.newSingleThreadExecutor()
is adequate for testing the non thread-safe code, despite the resulting program having two threads (the thread running the unit tests and the single thread-pool thread of the ExecutorService
). This is because an ExecutorService
must provide the following thread-safety guarantees:
- Actions in a thread prior to the submission of a
Runnable
orCallable
task to anExecutorService
happen-before any actions taken by that task, - which in turn happen-before the result is retrieved via
Future.get()
.
Therefore, if the thread running the unit tests does a Future.get()
for all the submitted tasks, all changes to any shared objects will have been safely published, and the thread running the unit tests may safely examine those shared objects.
来源:https://stackoverflow.com/questions/53169939/executor-suitable-for-non-thread-safe-code