HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Moving from normal threads to ExecutorService thread pools in java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
executorservicethreadsnormaljavamovingthreadpoolsfrom

Problem

I had my original threading code which worked well, but since my tasks were shortlived, I decided to use thread pools through ExecutorService.

This was my original code

public class MyRun implements Runnable
{
    private Socket socket = null;
    public MyRun(Socket s)
    {
        socket = s;
        thread = new Thread(this, "SocketThread");
        thread.start();
    }
    public void run()
    {
        // My actual thread code
    }
}


My main program

...
ss = new ServerSocket(port);
....
MyRun st = null;
while (!stop)
{
    st = new MyRun(ss.accept());
    st = null;
}


New code

public MyRun(Socket s)
{
    socket = s;
    thread = new Thread(this, "SocketThread");
}


run() left unchanged

Changed Main program

private static ExecutorService execService = Executors.newCachedThreadPool();
....
....
while (!stop)
{
    execService.execute(new MyRun(ss.accept()));
}


Changed code seems to be working fine, but I just want to make sure there is nothing I am missing. I want all threads to execute simultaneously.

Solution

A few simple remarks :

  • thread = new Thread(this, "SocketThread"); is no longer needed in MyRun, since the ExecutorService is the one creating and managing the Threads.



  • you will want to call execService.shutDown() to properly clean up the resources of the executorService.

Context

StackExchange Code Review Q#25763, answer score: 6

Revisions (0)

No revisions yet.