Search code examples
javamultithreadingconcurrencythreadpool

How can I avoid that each Thread creates a different pool?


In my program I have a class called "Vehicle" which extends from Thread, the thing is that at a certain point I need these Threads to create a Task (Runnable) and I want all these tasks to be managed by the same Threadpool, the problem is that if I call a method from a different class that contains this Pool, every other thread is creating a different pool. How can I avoid this? Thanks in advance.

public class Station {
    Arrivals arrivals;
    Vehicle k;
    ListPumps lp;

    ExecutorService executor = Executors.newFixedThreadPool(3);
    public synchronized void startWork(Pump p) {

        Runnable w = new Work(p);
        executor.execute(w);

        executor.shutdown();
        while (!executor.isTerminated()) {
    }
        System.out.println("Finished all threads");
     }
}

Solution

  • Your code already uses a single threadpool. However if your class might have several instances and you want those to all share the same threadpool then assign it as a static variable.

    Though I would also pull out the shutdown code to its own method too now. Also don't poll isTerminated, use awaitTermination.

    Something like the following:

    public class Station {
    
        private Arrivals arrivals;
        private Vehicle k;
        private ListPumps lp;
    
        private static ExecutorService executor = Executors.newFixedThreadPool(3);
    
        public void startWork(Pump p) {
            Runnable w = new Work(p);
            executor.execute(w);
        }
    
        public static synchronized void shutdown() {
            executor.shutdown();
            if(executor.awaitTermination(60, TimeUnit.SECONDS))
                System.out.println("Finished all threads");
            else
                System.out.println("Executor shutdown timed out");
        }
    }