All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.softicar.platform.common.core.thread.collection.ThreadKiller Maven / Gradle / Ivy

Go to download

The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.

There is a newer version: 50.0.0
Show newest version
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();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy