Tuesday, March 31, 2009

ScheduledThreadPoolExecutor vs. Timer (Java)

I read that the Timer object was replaced by the ScheduleThreadPoolExecutor class in a book on multi-threaded programming or maybe it was a book on design patterns. I stuck this information away in the back of my mind as I had previously written some code using the Timer class, and had been given Spring beans using timers.

Recently I started working on a something similar to my existing code using the Timer object. Since it was so similar I thought I would just copy my other project, modify it slightly, and be done with it. I ran into a problem where the execution of the code seemed to just stop without terminating the thread and no error message.

I switched to the Executor class and was able to get an error message. Apparently the Timer object has a problem with unchecked exceptions.

Then I switched over to the ScheduledThreadPoolExecutor - same thing. Execution hangs. No error message.

Here is a simple example of Executor:


public class ExampleExecutor
{
private static final int NTHREADS = 100;
private static final Executor exec
= Executors.newFixedThreadPool(NTHREADS);

public static void main(String args[]) {

while (true) {

Runnable task = new Runnable() {
public void run() {
doMyThing();
}

private void doMyThing(){
//do something
}

};

exec.execute(task);
}
}
}