Skip to content
Thach Hoang edited this page Jan 31, 2017 · 3 revisions

Multi-threading

Callables that rename threads

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:

Clone this wiki locally