How to ensure that tasks in the pool are completed until the program is completed?

I am currently working on a multi-threaded workflow program. Simply put, this extract of the program receives the object, passes it to the hasher method, minhash the value of the object and adds it to the list that needs to be manipulated to check the similarity.

My problem is that the main thread seems to be moving where I am manipulating the list while the threads from the pool are still running and minhashing the values ​​of the object using println. I could see that the program was running to the end, but the threads were still running in the run () method after.

How can I guarantee that the tasks in the pool must be completed before the program moves forward?

int docCount = 2;
    while (docCount > 0) {
        try {
            Shingle s = q.take();

            if (s instanceof Poisin == false) {
                pool.execute(new Runnable() {

                    @Override
                    public void run() {
                        System.out.println("DEBUG : currently in run()" + Thread.currentThread());

                        if (s.getDocumentId() == 1) {
                            list1.add(hasher(s));
                        } else if (s.getDocumentId() == 2) {
                            list2.add(hasher(s));
                        } else {
                            voidList.add(hasher(s));
                        }
                    }
                });// Runnable
            } else {
                docCount--;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("INteruppted exception " + e);
        }
    }

    float k1 = list1.size();
    float k2 = list2.size();
    System.out.println("DEBUG : End of program" + Thread.currentThread());
+4
2

, ?

, , , . shutdown .

pool.shutdown(); 

pool.awaitTermination(60, TimeUnit.SECONDS) // specify timeout here

Oracle ():

void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

, , ​​ 60 .

+3

- , .

<Submit work to thread pool>
..

executorService.shutdownNow();
executorService.awaitTermination();
..
<Process results from threads>
+1

Source: https://habr.com/ru/post/1692016/


All Articles