Pages

Thursday, March 19, 2009

Controlling threads in Java

I have written threaded applications that spawn threads to do specific bulk processing and I have written apps that spawn a thread to function as a daemon (e.g. watching a directory for a file). I have started these java daemons by a servlet that gets loaded on startup, but I found this was not the best way. If the context shuts down then the threads are left without a parent. This eats up Tomcat's memory every time I undeploy/deploy the app. A better way is to have a context listener that starts up the threads and keeps a handle to the thread object. When the context shuts down you can use the handle to shutdown the threads properly. To counter this I need to find some way to control the execution of the thread. Most daemon type processes use code similar to this:


// Sets up an infinite loop .
while (true)
{
// do the thread processing here.

}

I will alter this to be a Boolean value that I can change using some set methods in the object. This will provide me an interface for turning the thread on and off. Below is a partial listing of the class I end up with.

public class FileEvictor
{

private Boolean threadOn = true;
private int start = 1;
private int stop = 2;

private void init()
{
try
{
//Create background thread, which will be responsible for purging expired items.
Thread threadCleanerUpper = new Thread( new Runnable()
{

public void run()
{

System.out.println("File Evictor Service is running.");

try
{
// Sets up an infinite loop .
while (threadOn)
{
// do the thread processing here.

}
}
catch (Exception e)
{
System.out.println("Unknown exception" + e.getMessage());
e.printStackTrace();
}
finally
{
//TODO more info on what bombed
}
return;
}
}, "File Evictor"); // End class definition and close new thread definition

// Sets the thread's priority to the minimum value.
threadFileEvictor.setPriority( Thread.MIN_PRIORITY );

// Starts the thread.
threadFileEvictor.start();
}

public FileEvictor( int aStartHour, int aStopHour)
{
start = aStartHour;
stop = aStopHour;
init();

}
public void setThreadOn()
{
threadOn = true;
}
public void setThreadOff()
{
threadOn = false;
}



Once I have these start and stop methods in my thread, then all I have to do is create a context listener that will start the thread and stop the thread when the context comes up or down.

No comments:

Post a Comment