1

I have java code with jdk 1.7 like following which is doing parallel thread base implementation

ExecutorService executorService = Executors.newFixedThreadPool(currentRecordSize); executorService.execute((Runnable) someobject);

In logs i am getting thread name like

pool-2-thread-1 pool-2-thread-2 pool-1-thread-1 pool-1-thread-2

I wanted to suffix them with some string

Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93

2 Answers2

1

You can use a custom thread factory, for instance in Ehcache there's one implemented this way:

public class NamedThreadFactory implements ThreadFactory {

    private static AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Constructor accepting the prefix of the threads that will be created by this {@link ThreadFactory}
     * 
     * @param namePrefix
     *            Prefix for names of threads
     */
    public NamedThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    /**
     * Returns a new thread using a name as specified by this factory {@inheritDoc}
     */
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
    }

}

Then you can create your executor this way:

ExecutorService executor = Executors.newFixedThreadPool(currentRecordSize, new NamedThreadFactory("Your prefix here"));
Guillaume
  • 14,306
  • 3
  • 43
  • 40
  • Can i set private static AtomicInteger threadNumber = new AtomicInteger(1); as instance method as this is done in some sort of background job where this will be set per Factorybased count. – Kamran Shahid Sep 12 '20 at 08:21
  • i have given detail in My answer (just for reference purpose). Please suggest if it make sense. I am basically a C# active developer and done java development a decade back. so need bit help – Kamran Shahid Sep 12 '20 at 08:31
  • 1
    Yes sure, the threadNumber can be an instance variable instead of a static field, this was just an example. – Guillaume Sep 13 '20 at 10:23
0

My code with @Guillaume logic. only thing i am thinking is AtomicInteger field should be class level rather then static as after each loop new pool is created as per my logic

public void run() {
        log.info(name + " Started");
        ExecutorService executorService = null;
        
        while (true) {
            try {
                
                List<HashMap<String, String>> rows = QueryFromDB;
                int currentRecordSize = rows.size();                
                if (currentRecordSize > 0) {
                    NamedThreadFactory threadFactory = new NamedThreadFactory(name);
                    log.info(" *** " + name + " Initializing Executor . Received " + rows.size() + " txns.");
                    if (currentRecordSize < threadPoolSize) {
                        //executorService = Executors.newFixedThreadPool(currentRecordSize);
                        executorService = Executors.newFixedThreadPool(currentRecordSize, threadFactory);
                    } else {
                        //executorService = Executors.newFixedThreadPool(threadPoolSize);
                        executorService = Executors.newFixedThreadPool(threadPoolSize, threadFactory);
                    }
                    for (HashMap<String, String> row : rows) {
                                   MyClass obj = fromsomeclassmethod;
                                    if (obj instanceof Runnable) {
                                        executorService.execute((Runnable) obj);
                                    } else {
                                        obj.SomeMethod(..);
                                    }
                                    Thread.sleep(ThreadExecutorSleep);//some minor sleep like 10 miliseconds                                
                    }

                    if (!(executorService.isShutdown())) {
                        executorService.shutdown();
                        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                    }
                }                
                Thread.sleep(ADMSProcessor.fetchQueInterval);//1 second  sleep
            } catch (Exception ex) {
                log.fatal("Exception in " + name + " Thread :" + ex);
            }
        }
    }




public class NamedThreadFactory implements ThreadFactory {

    //private static AtomicInteger threadNumber = new AtomicInteger(1);
    private AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Constructor accepting the prefix of the threads that will be created by this {@link ThreadFactory}
     *
     * @param namePrefix
     *            Prefix for names of threads
     */
    public NamedThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    /**
     * Returns a new thread using a name as specified by this factory {@inheritDoc}
     */
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
    }
}
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93