Java Thread Pool: Is the thread renewed?

advertisements

I have a Thread pool in my Java.NIO socket server. I sometimes received runtime errors like Connection reset by peer or Broken Pipe, etc.

My question is: is the thread getting killed when an exception is thrown? If it is - is a new thread created in the thread pool in place of the killed thread??

This is my ThreadManager:

import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadsManager {

    private ExecutorService threadPool = null;
    private LiveConnectionsManager liveConnectionsManager;
    private int threadPoolSize = 35; //number of tasks thread

    public ThreadsManager(LiveConnectionsManager liveConnectionsManager) {
        this.liveConnectionsManager = liveConnectionsManager;
        threadPool = Executors.newFixedThreadPool(threadPoolSize);
        ServerActions.threadPool = threadPool;
    }

    public void processNewMessage(SocketChannel socketChannel, Client client)
    {
        threadPool.execute(new MessagesProcessor(socketChannel, client, liveConnectionsManager));
    }

    public void closeConnection(SocketChannel socketChannel, Client client) {
        threadPool.execute(new LogoutClient(socketChannel, client, null));
    }
}


As you using ExecutorService to create thread pool.

So yes, ExecutorService.newFixedThreadPool(..) ensures that number of threads are constant if they get killed by any exception/error and there are enough task waiting for thread. Below text from java doc states it clearly :

Straight from java doc :newFixedThreadPool

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)