1

I'm trying to set names to thread, but ExecutorService sets its own (like pool-1-thread-1). Question Naming threads and thread-pools of ExecutorService give the advice to use ThreadFactory. Ask you to consider this solution, is it safe enough?

public class Test {
    private volatile String prName;
    private volatile boolean prIsDaemon;

    private final ExecutorService pool = Executors.newCachedThreadPool(
        (Runnable r) -> {
            final Thread t = new Thread( r, prName );
            t.setDaemon( prIsDaemon );
            return t;
        }
    );

    public void Submit(boolean daemon, String name, Runnable run) {
        prIsDaemon = daemon;
        prName = name;
        pool.submit( run );
    }

    public void Shutdown() {
        pool.shutdown();
    }

    public static void main(String[] args) {
        final Test test = new Test();
        final Runnable r = () -> {
            System.out.println( Thread.currentThread().getName() );
        };
        test.Submit( false, "aaa", r );
        test.Submit( false, "bbb", r );
        test.Shutdown();
    }
}

RESULT:

aaa
bbb
Community
  • 1
  • 1
Dmitry
  • 105
  • 1
  • 9
  • 1
    No. Your method naming is wrong - in Java methods are always named in `camelCase`; `PascalCase` is reserved for classes **only**. No exceptions. No excuses. – Boris the Spider Oct 18 '16 at 15:46
  • Also, a **mutable** `ThreadFactory` with a `newCachedThreadPool` is a **terrible**, **TERRIBLE** idea. For so, so many reasons. In fact, a mutable `ThreadFactory` is a terrible idea, always. Throw this all away and start again. – Boris the Spider Oct 18 '16 at 15:48
  • It's better to use an ExecutorService provided by your application server if you have a j2ee container – Javier Toja Oct 18 '16 at 15:49
  • 2
    No, this code is not safe. a) you will have issues when you concurrently submit jobs b) a cached thread pool will reuse threads, so they will not all get a new name every time – Thilo Oct 18 '16 at 15:50
  • @karelss what does that have to do with anything? This is obviously a standalone application. – Boris the Spider Oct 18 '16 at 15:50
  • @BoristheSpider well it's not so obious to me because he only show test code as an example, not the real case – Javier Toja Oct 18 '16 at 15:51
  • You should not use the thread name for anything important. It's just for logging and stuff. If you need to pass an important String to your Runnable, pass it to your Runnable directly. If you really need something "global", consider a ThreadLocal (that your ExecutorService can setup and remove). – Thilo Oct 18 '16 at 15:52
  • @karelss if the question has a `main` method and Java EE is not mentioned anywhere in the text. Nor in a tag. It is safe at assume that Java EE is not being asked about. – Boris the Spider Oct 18 '16 at 15:52
  • 1
    When you are using an ExecutorService, you Runnables should be agnostic to the mechanism executing them. – Mahesh Oct 19 '16 at 02:19

0 Answers0