de.thksystems.util.concurrent.NamedCallable Maven / Gradle / Ivy
/*
* tksCommons
*
* Author : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de)
* License : LGPL (https://www.gnu.org/licenses/lgpl.html)
*/
package de.thksystems.util.concurrent;
import java.util.concurrent.Callable;
/**
* A {@link Callable} with the ability to set the thread-name that is used while calling.
*/
public class NamedCallable implements Callable {
private final Callable callable;
private String threadName;
private NamedCallable(Callable callable) {
this.callable = callable;
}
@Override
public V call() throws Exception {
String oldThreadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(threadName);
V result = callable.call();
return result;
} finally {
Thread.currentThread().setName(oldThreadName);
}
}
public static NamedCallable of(Callable callable) {
return new NamedCallable<>(callable);
}
public NamedCallable withThreadName(String threadName) {
this.threadName = threadName;
return this;
}
}