Search code examples
javamultithreadingfuturetask

Multithreading - Naming threads and handling exceptions


In java, what are the suggested ways to implement the two thread requirements

  1. I would like the name a thread
  2. I would like the parent (or main) thread know if there are any exceptions by this child thread.

For 2, I understand that having a future object would be a better approach. So to implement the above two requirements below is a code I came up with

class MyRunnable implements Runnable {
  ....
}


MyRunnable myRunnable = new MyRunnable ();
FutureTask futureTask = new FutureTask(myRunnable, null);
Thread myThread = new MyThread(futureTask, "processing-thread");
myThread.start();
try {
   futureTask.get();
} catch (Exception e) {
   throw new RuntimeException(e)
}

This seems to be a lot of code for simple stuff. Any better ways?

Note - Using executorService is not an option since I have threads which are not doing similar tasks. Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.


Solution

  • Using executorService is not an option since I have threads which are not doing similar tasks.

    I don't see how this would matter.

    Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.

    So give each thread a name with a ThreadFactory. I have a class which I call a NamedThreadFactory.

    I suspect what you would like the thread to do is reflect what the task is doing.

    You can do this

    ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(new Runnable() {
        public void run() {
            Thread.currentThread().setName("Working on task A");
            try {
                System.out.println("Running: "+Thread.currentThread());
            } finally {
                Thread.currentThread().setName("parked worker thread");
            }
        }
    });
    es.shutdown();
    

    prints

    Running: Thread[Working on task A,5,main]
    

    BTW There is no point starting a thread and immediately waiting for it to finish. You may as well use the current thread.