Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give name to a callable Thread? [duplicate]

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?

like image 584
user381878 Avatar asked Jul 12 '10 08:07

user381878


People also ask

How do you add a name to a 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.

Can two threads have same name?

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.

How do you call a Callable thread?

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.

How do you name a runnable in Java?

Thread thread = new Thread(runnable Task); thread. setName("My Thread Name");


1 Answers

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);             }         }     }); 
like image 101
Bart van Heukelom Avatar answered Sep 22 '22 18:09

Bart van Heukelom