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

com.softicar.platform.common.core.thread.collection.ThreadJoiner 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;

import com.softicar.platform.common.core.threading.Threads;

/**
 * This class joins a set of thread until a given timeout.
 *
 * @author Oliver Richers
 */
public class ThreadJoiner {

	private final ThreadCollection threads;
	private long deadline;

	public ThreadJoiner(ThreadCollection threads) {

		this.threads = new ThreadCollection<>(threads);
	}

	public boolean joinAll(long timeoutMillis) {

		this.threads.removeFinishedThreads();
		this.deadline = System.currentTimeMillis() + timeoutMillis;

		do {
			joinFirstThread();
			threads.removeFinishedThreads();
		} while (!threads.isEmpty() && System.currentTimeMillis() <= deadline);

		return threads.isEmpty();
	}

	private void joinFirstThread() {

		threads//
			.stream()
			.findFirst()
			.ifPresent(this::joinThread);
	}

	private void joinThread(Thread thread) {

		Threads.join(thread, getRestTimeout());
	}

	private long getRestTimeout() {

		return Math.max(1, deadline - System.currentTimeMillis());
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy