* don't keep unused threads around

This commit is contained in:
Reinhard Pointner 2009-10-15 15:18:57 +00:00
parent d841b76fc4
commit 5bb45541a8
1 changed files with 22 additions and 24 deletions

View File

@ -4,39 +4,44 @@ package net.sourceforge.tuned;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public abstract class Timer implements Runnable {
private final ScheduledThreadPoolExecutor executor;
private final ThreadFactory threadFactory = new DefaultThreadFactory("Timer", Thread.NORM_PRIORITY, true);
private ScheduledThreadPoolExecutor executor;
private ScheduledFuture<?> scheduledFuture;
private Thread shutdownHook;
public Timer() {
executor = new ScheduledThreadPoolExecutor(1, new DefaultThreadFactory("Timer", Thread.NORM_PRIORITY, true));
public synchronized void set(long delay, TimeUnit unit, boolean runBeforeShutdown) {
// create executor if necessary
if (executor == null) {
executor = new ScheduledThreadPoolExecutor(1, threadFactory);
}
// cancel existing future task
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
public synchronized void set(long delay, TimeUnit unit, boolean runBeforeShutdown) {
removeScheduledFuture();
Runnable r = this;
Runnable runnable = this;
if (runBeforeShutdown) {
addShutdownHook();
// remove shutdown hook after execution
r = new Runnable() {
runnable = new Runnable() {
@Override
public void run() {
try {
Timer.this.run();
} finally {
removeShutdownHook();
cancel();
}
}
};
@ -45,25 +50,18 @@ public abstract class Timer implements Runnable {
removeShutdownHook();
}
scheduledFuture = executor.schedule(r, delay, unit);
scheduledFuture = executor.schedule(runnable, delay, unit);
}
public synchronized void cancel() {
removeScheduledFuture();
removeShutdownHook();
}
// stop executor
executor.shutdownNow();
private synchronized void removeScheduledFuture() {
if (scheduledFuture != null) {
try {
scheduledFuture.cancel(true);
executor.purge();
} finally {
scheduledFuture = null;
}
}
executor = null;
}