Friday, 10 January 2014

Java - every thread deserves a name

The Java concurrency API makes it very easy to create a thread pool. You can just use the following statement:

ExecutorService executor = Executors.newFixedThreadPool(4);

However, when looking in the debugger, or the output of logs, the threads will appear with the unhelpful names:

Thread [pool-1-thread-1] (Running)
Thread [pool-1-thread-2] (Running)
Thread [pool-1-thread-3] (Running)
Thread [pool-1-thread-4] (Running)

In a large application, you may be using a number of executors, which means you have no idea which threads are running, and things can get very frustrating. 

Luckily there is a solution - all Executors allow the provision of a ThreadFactory implemenation during construction. 

Below is an implementation of a ThreadFactory that gives every thread a name:

public class NamedThreadFactory implements ThreadFactory
    private int threadCount ;
    private final String prefix ;
    public NamedThreadFactory( String prefix )
        this.prefix = prefix ;

    public Thread newThread(Runnable r)
        return new Thread(r, prefix + "-" + ++threadCount);

Which can be used to create the thread pool as:

ExecutorService executor = 
     Executors.newFixedThreadPool(10, new NamedThreadFactory("CalculatePrice");

Now when we run the application we'll see the following threads, which gives us a much clearer indication of what is running.

Thread [CalculatePrice-1] (Running)
Thread [CalculatePrice-2] (Running)
Thread [CalculatePrice-3] (Running)
Thread [CalculatePrice-4] (Running)

So if you're going to create lots of threads - please give them a name - it does make a difference.

Tuesday, 7 January 2014

Happy 2014

Just wishing everyone a happy and prosperous new year. Lets hope its an exciting one.