I am executing a Callable Object using ExecutorService thread pool. I want to give a name to this thread.
To be more specific, in older version I did this -
Thread thread = new Thread(runnable Task); thread.setName("My Thread Name");
I use thread name in log4j logging, this helps a lot while troubleshooting. Now I am migrating my code from Java 1.4 to Java 1.6. I have written this(Given below)- but I dont know how to give name to this thread.
private final ExecutorService executorPool = Executors.newCachedThreadPool(); Future<String> result = executorPool.submit(callable Task);
Please give me some idea to give name to this thread?
You can give a name to a thread by using setName() method of Thread class. You can also retrieve the name of a thread using getName() method of a Thread class. These two methods are public and final.
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
Each thread invokes the call() method, generates a random number, and returns it. The get() method is used to receive the returned random number object obtained from the different threads to the main thread. The get() method is declared in the Future interface and implemented in the FutureTask class.
Thread thread = new Thread(runnable Task); thread. setName("My Thread Name");
I'm currently doing it somewhat like this:
someExecutor.execute(new Runnable() { @Override public void run() { final String orgName = Thread.currentThread().getName(); Thread.currentThread().setName(orgName + " - My custom name here"); try { myAction(); } finally { Thread.currentThread().setName(orgName); } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With