Friday, May 18, 2007

Java Threading - ScheduledExecutorService

Today I stummbled upon something I had not done, this may be old hat for some of you, but none the less I thought it was pretty cool and thought I would share. I was working on a class that needed to kick off a thread, so i started down the path I knew and created a class that implemented Runnable, created the run method, and it looked something like the following:


public class MyThread implements Runnable {
private Boolean running;

public MyThread(Boolean running) {
this.running = running;
}

public void run() {
while (running) {
process();
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}

public void process() {
//Do someting cool here
}

public void setRunning(Boolean running) {
this.running = running;
}
}

public class ExecuteThread {
private Boolean running = true;
private MyThread myThread;

public void activate() {
myThread = new MyThread(running);
Thread thread = new Thread(myThread);
thread.start();
}

public void deactivate() {
myThread.setRunning(false);
}
}


Using the ScheduledExecutorService provided in the java.util.concurrent package you can handle the execution of a thread and control the initial delay, delay, and the unit of time with one method call. Something like the following:

public class MyThread implements Runnable {
public MyThread() {
}

public void run() {
process();
}

public void process() {
//Do something cool here
}
}

public class ExecuteThread {
private MyThread myThread;
private final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();

public void activate() {
myThread = new MyThread();
scheduler.scheduleWithFixedDelay
(myThread, 0, 10, TimeUnit.SECONDS);
}

public void deactivate() {
scheduler.shutdown();
}
}

Again, this might be old news for some of you, but I thought this was a very effective way to handle threading and it really cleaned up my code in the end.

7 comments:

Leon said...

Thanks for that, I found it very helpful.

Azer AYOUB said...

A simple but useful example, good work!

Anu said...

good one dude!!!

Nii Amah said...

Thanks, that was a nice concise example. Just what I was looking for.

leandro.prates said...

If you were a good programmer like me you would have used Quartz. But you showed us that you are a simple programmer.

Anonymous said...

what import did you use for your program. I tried to use import static java.util.concurrent.TimeUnit.*; but that doesn't seem to work.

Anonymous said...

Really usefull