1

I have a ExecutorService and ScheduledExecutorService for which I am using custom ThreadFactory so that I can name every thread as per type of runnable input to Thread factory for thread creation, but the input runnable to ThreadFactory is of type ThreadPoolExecutor$Worker. Following is my ThreadFactory implemntation. How can I get actual runnable from ExecutorService and ScheduledExecutorService for thread creation?

AcquirerTransaction & IssuerTransaction implements Runnable.

private final ThreadFactory               threadFactory = new CustomThreadFactory(config.bankId, config);
private final ScheduledThreadPoolExecutor schedular     = new ScheduledThreadPoolExecutor(5, threadFactory);
private final ThreadPoolExecutor          executor      = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);


public final class CustomThreadFactory implements ThreadFactory {
    private final String     prefix;
    private final CoreConfig config;
    private AtomicInteger    counter = new AtomicInteger(0);

    public CustomThreadFactory(final String prefix, final CoreConfig config) {
        this.prefix = prefix;
        this.config = config;
    }

    //@formatter:off
    @Override
    public final Thread newThread(Runnable runnable) {
        if(runnable instanceof Scheduled) return new Thread(runnable, getName(prefix, "sch", counter.getAndIncrement()));
        else if (runnable instanceof AcquirerTransaction || runnable instanceof NoLogAcquirerTransaction) return new Thread(runnable, getName(prefix, "acq", counter.getAndIncrement()));
        else if (runnable instanceof IssuerTransaction || runnable instanceof NoLogIssuerTransaction) return new Thread(runnable, getName(prefix, "iss", counter.getAndIncrement()));
        else return new Thread(runnable, getName(prefix, "gen", counter.getAndIncrement()));
    }

    private static final String getName(final String prefix, final String type, final int count) {
        return prefix + "-" + type + "-" + count;
    }


    public final String getPrefix() {
        return prefix;
    }
}
Robur_131
  • 374
  • 5
  • 15
krishna T
  • 425
  • 4
  • 14

1 Answers1

1

You could set the current thread's name at start of runnable execution and clear it at end. Use the static curentThread method to obtain the Thead ans then the setName method.

cquezel
  • 3,859
  • 1
  • 30
  • 32