Nullpointer
Nullpointer

Reputation: 1086

Java ExecutorService - Creating a new thread but not starting it

I came across below code snippet while reading ExecutorService section from book Java 8 The complete reference.

Below code snippet explains how ExecutorService works.

// A simple example that uses an Executor.

import java.util.concurrent.*;

class SimpExec {

    public static void main(String args[]) {
        CountDownLatch cdl = new CountDownLatch(5);
        CountDownLatch cdl2 = new CountDownLatch(5);
        CountDownLatch cdl3 = new CountDownLatch(5);
        CountDownLatch cdl4 = new CountDownLatch(5);
        ExecutorService es = Executors.newFixedThreadPool(2);
        System.out.println("Starting");
        // Start the threads.
        es.execute(new MyThread(cdl, "A"));
        es.execute(new MyThread(cdl2, "B"));
        es.execute(new MyThread(cdl3, "C"));
        es.execute(new MyThread(cdl4, "D"));
        try {
            cdl.await();
            cdl2.await();
            cdl3.await();
            cdl4.await();
        } catch (InterruptedException exc) {
            System.out.println(exc);
        }
        es.shutdown();
        System.out.println("Done");
    }
}

class MyThread implements Runnable {

    String name;
    CountDownLatch latch;

    MyThread(CountDownLatch c, String n) {
        latch = c;
        name = n;
        new Thread(this);
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + ": " + i);
            latch.countDown();
        }
    }
}

What I am not able to understand is the last line in the constructor of class MyThread.

The constructor of MyThread creates an Object of Thread using

new Thread(this)

However, this newly created thread is never started by calling start() method. Also, according to my understanding ExecutorService creates and manages its own threads to run our runnable task. Then why is this Thread object being created in this case?

Upvotes: 2

Views: 2093

Answers (1)

this line:

new Thread(this);

is taking no effect on the execution of the code and you can removed without a problem...

the executor will create its own thread in order to execute the code

you can verify that this line of code is not taking effects by:

  1. removing the line from the code (it will get the same result)
  2. giving a name to the thread and debuggin new Thread(this, "T: " + n); you will see that no thread with such a name appears in the stack
  3. you can cehck the source code of the ThreadPoolExecutor and verify that the method private boolean addWorker(Runnable firstTask, boolean core) is creating a new worker from the runnable you gave as parameter and from that they do

--

w = new Worker(firstTask);
final Thread t = w.thread;

Upvotes: 2

Related Questions