Tuesday, January 24, 2006

ThreadEntryPoint in Java (1.4.x)

I needed a ThreadEntryPoint in a Java project.
Since I failed to find a existing implementation of this tool, I wrote one myself.
Do you know if I missed a better implementation? Tell me!


ThreadEntryPoint
The idea is that we have several small tasks that can be executed by several concurrent threads. The threads are normally a part of a threadpool.
Sometimes a subset of these tasks should be performed in a certain order, one at a time. An example could be when you controll several telephones; if you issue a "lift-hook" to the telephony subsystem no other calls should be performed at the same time. It is usually much simpler to write the code when you know that no other task will change member variables in the Telephone object.

ThreadEntryPointHandler.java
The external API is:


public class ThreadEntryPointHandler
{
public void PostMsg(Object entryPointID, Runnable task);
}


When you issue a task with a new entrypoint ID a new entrypoint is created and the execution starts. If you would add another task while the first is running the second is placed in the entrypoints internal queue. When the queue is empty the entrypoint removes itself (to save threads in the system).

The problems encountered when implementing is making sure that creating and destroying entrypoints without problems due to concurrency. I simply solved this by synchronizing on the handler a little more then really needed, and thereby avoiding the philosophers problem.

0 Comments:

Post a Comment

<< Home