com.softicar.platform.common.core.thread.collection.ThreadKiller Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of platform-common Show documentation
Show all versions of platform-common Show documentation
The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.
package com.softicar.platform.common.core.thread.collection;
/**
* This class tries to kill one or more threads by calling
* {@link Thread#interrupt()}.
*
* @author Oliver Richers
*/
public class ThreadKiller {
private static final int DEFAULT_TRY_COUNT = 5;
private static final long DEFAULT_TIMEOUT = DEFAULT_TRY_COUNT * 1000;
private final ThreadCollection threads;
private long timeout;
private int tryCount;
public ThreadKiller(T thread) {
this(new ThreadCollection<>(thread));
}
public ThreadKiller(ThreadCollection threads) {
this.threads = new ThreadCollection<>(threads);
this.timeout = DEFAULT_TIMEOUT;
this.tryCount = DEFAULT_TRY_COUNT;
}
public ThreadKiller setTimeout(long timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("Kill timeout must be at least 0.");
}
this.timeout = timeout;
return this;
}
public ThreadKiller setTryCount(int tryCount) {
if (tryCount < 1) {
throw new IllegalArgumentException("Kill try count must be at least 1.");
}
this.tryCount = tryCount;
return this;
}
public boolean killAll() {
for (int i = 0; i < tryCount && !threads.isEmpty(); i++) {
killThreads();
}
return threads.isEmpty();
}
private void killThreads() {
threads.interruptAll();
threads.joinAll(Math.max(1, timeout / tryCount));
threads.removeFinishedThreads();
}
}