de.thksystems.util.concurrent.NamedConsumer 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.function.Consumer;
/**
* A {@link Consumer} with the ability to set the thread name that is used while calling.
*/
public class NamedConsumer implements Consumer {
private final Consumer consumer;
private String threadName;
protected NamedConsumer(Consumer consumer) {
this.consumer = consumer;
}
public static NamedConsumer of(Consumer consumer) {
return new NamedConsumer<>(consumer);
}
@Override
public void accept(V t) {
String oldThreadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(threadName.replace("{thread-id}", String.valueOf(Thread.currentThread().getId())));
consumer.accept(t);
} finally {
Thread.currentThread().setName(oldThreadName);
}
}
}