Search code examples
javamultithreadingthreadpoolthreadpoolexecutor

ThreadPoolExecutor : awaiting termination outside the method


Current scenario : My code (let say "Class Caller : caller()") is going to call a method of a class (Class ThreadPoolClass : writeData()) which internally executes it's task via ThreadPoolExecutor. Now this implementation doesn't wait for the termination of all of it's tasks.

Issue : While my code (method caller()) needs to wait until all the tasks from this (method writeData() )ThreadPoolExecutor are finished. Currently the controller comes back to caller() method after submitting the tasks.

ThreadPoolClass's implementation cannot be changed, that's why I wanted to figure out that how can I achieve this.

//Sample code

class Caller {
    public static void main(String[] args) {
        ThreadPoolClass t = new ThreadPoolClass();
        t.writeData();

        // I want to wait here until the execution is complete
    }
}

class ThreadPoolClass{
    void writeData() {
        Runnable thread = new Runnable() {

            @Override
            public void run() {
                //  Do some database commit operations

            }
        };
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        fixedThreadPool.submit(thread);
        fixedThreadPool.shutdown();
    }
}

Any heads up will be helpful - even whether it is possible or not.

Note** this is just a sample, my original code has a chain of class-method calls which eventually executes the method with ThreadPoolExecutor.

Thanks Dish


Solution

  • Thanks everyone for inputs. So based on above comments and some analysis from my end too I am assuming that this cannot be achieved. The summarized comments :

    I do not see a possibility without changing the ThreadPoolClass's code except to write a new Class doing the same but with the possibility to wait/block or callback. – Fildor

    Is it an option to just copy the "Do some database commit operations" and execute them sequentially on the main thread? Reusing code is great but that API makes it impossible as it is.