de.thksystems.util.concurrent.NamedCallable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cumin Show documentation
Show all versions of cumin Show documentation
Commons for lang, crypto, xml, dom, text, csv, reflection, annotations, parsing, ...
/*
* 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;
protected NamedCallable(Callable callable) {
this.callable = callable;
}
public static NamedCallable of(Callable callable) {
return new NamedCallable<>(callable);
}
@Override
public V call() throws Exception {
String oldThreadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(threadName.replace("{thread-id}", String.valueOf(Thread.currentThread().getId())));
return callable.call();
} finally {
Thread.currentThread().setName(oldThreadName);
}
}
/**
* Sets the thread name.
*
* If the thread name may contains "{thread-id}", it will be substituted with the id of the thread.
*/
public NamedCallable withThreadName(String threadName) {
this.threadName = threadName;
return this;
}
}