-
Notifications
You must be signed in to change notification settings - Fork 0
Java
Thach Hoang edited this page Jan 31, 2017
·
3 revisions
- Never use java.util.Timer in Java EE
- Multithreaded code and concurrency
- How to find a concurrency bug with java?
You want to submit a Callable to a thread pool executor. When the Callable is executed, you want to append a unique ID to the thread name.
Looks like the perfect opportunity to use some AspectJ magic. You find this useful cheat sheet.
Define this annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ThreadRename {
String suffix();
}It's possible to define a pointcut that extracts a field on an annotation. Work in progress:
Object around(): execution(@domain.whatever.ThreadRename * *(..)){
final String threadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(threadName + "-ID=");
return proceed();
} finally {
Thread.currentThread().setName(threadName);
}
}At this point you remember that annotation fields can only be set to constant values.
Keep it simple.
public abstract class ThreadRenamingCallable<V> implements Callable<V> {
private final String suffix;
public ThreadRenamingCallable(String suffix) {
this.suffix = suffix;
}
public abstract V get() throws Exception;
@Override
public final V call() throws Exception {
final String threadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(threadName + suffix);
return get();
} finally {
Thread.currentThread().setName(threadName);
}
}
}Interestingly:
- Guava as of 18.0 does not already have this class.
- As of April 29, 2015, there is one public project containing the exact same class with the exact same name.