org.sentrysoftware.metricshub.engine.common.helpers.ThreadHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of metricshub-engine Show documentation
Show all versions of metricshub-engine Show documentation
MetricsHub Monitoring Engine
The newest version!
package org.sentrysoftware.metricshub.engine.common.helpers;
/*-
* ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
* MetricsHub Engine
* ჻჻჻჻჻჻
* Copyright 2023 - 2024 Sentry Software
* ჻჻჻჻჻჻
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
* ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
*/
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Provides utility methods for thread management, including executing tasks
* with a specified timeout. This class is part of the MetricsHub Engine's
* common helper utilities.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadHelper {
/**
* Executes a {@link Callable} task with a specified timeout. This method
* creates a single-threaded executor to run the provided task. If the task
* completes within the given timeout, its result is returned. Otherwise, a
* {@link TimeoutException} is thrown.
*
* @param the type of the result returned by the {@code callable}
* @param callable the task to be executed
* @param timeout the maximum time to wait for the task to complete, in seconds
* @return the result of the executed task
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws ExecutionException if the computation threw an exception
* @throws TimeoutException if the wait timed out
*/
public static T execute(final Callable callable, final long timeout)
throws InterruptedException, ExecutionException, TimeoutException {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
final Future handler = executorService.submit(callable);
return handler.get(timeout, TimeUnit.SECONDS);
} finally {
executorService.shutdownNow();
}
}
}