Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

java - Executor suitable for non thread-safe code

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 Executors 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...