Executor suitable for non thread-safe code

為{幸葍}努か 提交于 2019-11-29 14:45:16

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 or Callable task to an ExecutorService 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!