Sunday, February 10, 2013

Interrupting a Thread in Java 7

In order to construct a well-behaved server class in Java, a few key pieces are required.  While researching this topic, I've discovered that there are n developers in the world working with Java concurrency and there are at least (n+1) opinions on the "proper way" to do this.   I've leveraged what seems to be the most common implementation guidelines and came up with the following example.

A few general notes:
  • there is much of anything in this example that is Java 7 specific, it just happens to be the version I'm using.
  • since this site is hosted on blogger, and there are not too many good/convenient options for presenting source code, I've just posted screen snapshots of the code.  My apologies for the laziness...

CONSOLE OUTPUT:

Jumping first to the summary, here is the program execution. You can see the server start, launch the worker thread, let it run for a short time, then signal the worker to stop.  All appears in order and working well.


APPLICATION CLASS:

Nothing too exciting to discuss here...  The main driver class to launch the example.


WORKER CLASS:

Here is the worker, a subclass of Thread.  This could be done by implementing a Runnable instead, but I find the Thread extension cleaner to read - mileage may vary based on personal preferences.  The worker does not perform any real work, but just dumps the message "worker thread performs work" to the console, then suspends.



SERVER CLASS:

Here is the implementation of the server (in order to keep the snapshot a bit cleaner, the shutdown method was extracted).  There are basic methods for startup and shutdown, as well as a simulate method which simulates work by for waiting for a short time.


SERVER SHUTDOWN METHOD:

This is the key to the whole process of stopping.  When the server shuts down, the worker thread needs to be asked to stop as well.  The server then waits for the worker to stop and then continues on with its own cleanup.  This method is really where implementations will tend to differ, based on what the worker thread is doing as well as the nature of the server itself.  You can use workerThread.join() to wait forever, but if the worker thread is hung, your server will never return.  This is one of those instances where you'll just need to apply best engineering judgement based on specifics to your application.


While researching Java concurrency, I did not find many full examples online; most tended to be snippets with too little, or full open source applications with too much.  I hope this example application finds a balance of both and is of use to someone else.

No comments:

Post a Comment