improve robustness and clarity of SingleThreadExecutorUtils.java (#1378)

This commit is contained in:
XMRZombie 2024-11-10 13:39:12 +00:00 committed by GitHub
parent 2a45ebe565
commit b31758e884
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -11,8 +11,8 @@
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public
* License along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package haveno.common.util;
@ -25,38 +25,67 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Utility class for creating single-threaded executors.
*/
public class SingleThreadExecutorUtils {
private SingleThreadExecutorUtils() {
// Prevent instantiation
}
public static ExecutorService getSingleThreadExecutor(Class<?> aClass) {
String name = aClass.getSimpleName();
return getSingleThreadExecutor(name);
validateClass(aClass);
return getSingleThreadExecutor(aClass.getSimpleName());
}
public static ExecutorService getNonDaemonSingleThreadExecutor(Class<?> aClass) {
String name = aClass.getSimpleName();
return getSingleThreadExecutor(name, false);
validateClass(aClass);
return getSingleThreadExecutor(aClass.getSimpleName(), false);
}
public static ExecutorService getSingleThreadExecutor(String name) {
validateName(name);
return getSingleThreadExecutor(name, true);
}
public static ListeningExecutorService getSingleThreadListeningExecutor(String name) {
validateName(name);
return MoreExecutors.listeningDecorator(getSingleThreadExecutor(name));
}
public static ExecutorService getSingleThreadExecutor(ThreadFactory threadFactory) {
validateThreadFactory(threadFactory);
return Executors.newSingleThreadExecutor(threadFactory);
}
private static ExecutorService getSingleThreadExecutor(String name, boolean isDaemonThread) {
final ThreadFactory threadFactory = getThreadFactory(name, isDaemonThread);
ThreadFactory threadFactory = getThreadFactory(name, isDaemonThread);
return Executors.newSingleThreadExecutor(threadFactory);
}
private static ThreadFactory getThreadFactory(String name, boolean isDaemonThread) {
return new ThreadFactoryBuilder()
.setNameFormat(name)
.setNameFormat(name + "-%d")
.setDaemon(isDaemonThread)
.build();
}
private static void validateClass(Class<?> aClass) {
if (aClass == null) {
throw new IllegalArgumentException("Class must not be null.");
}
}
private static void validateName(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Name must not be null or empty.");
}
}
private static void validateThreadFactory(ThreadFactory threadFactory) {
if (threadFactory == null) {
throw new IllegalArgumentException("ThreadFactory must not be null.");
}
}
}