In my application, the following situation: there is a тред типа А and a lot of тредов типа Б , in addition to this there is a main thread. In thread A, an error occurs, after which it is necessary immediately, or as soon as possible to close all threads B and the main thread, or to close threads B and transfer control to the main thread, which by some flag must understand what happened and take some actions before closing applications. Threads B must be closed as quickly as possible, because they run resource-intensive processes, the start of which becomes meaningless in case of an error in thread A.

Can someone from experienced developers give a beginner a variant of the algorithm (preferably with an example), when all this would be possible without using System.exit() ?

  • You just seem to need to take a actor-based framework - etki

1 answer 1

And what is there to invent algorithms? If you are using pure Thread , I recommend looking in the java.util.concurrent package towards ExecutorService , etc. In particular, in your task you can start stream A in one Executor , and stream B in another, catch error A of execution of stream A, and if it happens, simply close Executor with threads B (call shutdownNow ).

UPD

 class A implements Runnable { public void run(){} } class B implements Runnable { public void run(){} } 

And a sketch of how it works:

 ExecutorService executorA = Executors.newSingleThreadExecutor(); ExecutorService executorB = Executors.newCachedThreadPool(); Future<?> futureA = executorA.submit(new A()); List<Future<?>> futuresB = new ArrayList<>(); for(...){ futuresB.add(executorB.submit(new B())); } try { futureA.get(); } catch (InterruptedException e) { //process } catch (ExecutionException e) { executorB.shutdownNow(); //or //futuresB.forEach(f -> f.cancel(true)); //executorB.shutdown(); } executorA.shutdown(); //futuresB.forEach(f -> f.get()); 
  • Well, do not forget to carry out all operations with ports and other resources in the try-catch-finally construct, where in the finally block we try to close the port if it is still open. - DimXenon
  • I do not quite understand how to apply to my case. The fact is that I have thread A running to check the availability of authorization and install it if necessary, and only after a 10 second pause the threads of the B are started. Meanwhile, thread A continues to run and once every 30 minutes it checks the authorization again and, if necessary, sets it, and in case of an error when trying to log in and gives an error, at which it is necessary to stop B. threads. - Alex
  • In other words, it is clear how to close the Executor with threads B, but it is not clear where and how I should catch the flow error A. - Alex