What is the correct way to stop the flow under certain conditions?

some thread performs a series of operations in its run method. When the station is closed, it will onStationClosed all its passengers via onStationClosed . When this happens, the thread must take some action (for example, leave Station), and the thread must terminate without completing all stop operations.

What is the correct way to do this:

 // 1 - By checking station state between each operationN? public class Passenger extends Thread { Station station; public void onStationClosed() { // Do some action before thread terminates } @Override public void run() { operation1(); if(station.getState == Station.Closed) return; operation2(); if(station.getState == Station.Closed) return; operation3(); if(station.getState == Station.Closed) return; .. operationN(); } } // 2 - Throw StationClosedException from onStationClosed and catch it in Station. public class Passenger extends Thread { Station station; public void onStationClosed() { // Do some action before thread terminates throw new StationClosedException(); } @Override public void run() { operation1(); operation2(); .. operationN(); } } 
+4
source share
1 answer

The first solution is not bad. However, it’s not very , consider moving operations to some small action objects and check the status of the station before each operation:

 List<Operation> operations = Arrays.asList(new Operation1(), new Operation2(), new Operation3()); for(Operation operation: operations) { if(!perform(operation)) { return; } } 

Where perform() is defined as follows:

 private boolean perform(Operation operation) { if(station.getState == Station.Closed) return false; operation.run(); return true; } 

A bit far, but when the number of operations increases, you will appreciate it.

I do not quite understand the solution to the exception. If you throw this exception from the onStationClosed() callback, it will be thrown back to the event sender stream, not the Passenger thread. It will not interrupt your flow.

However, you can control this thread using InterruptedException . This solution is very similar to checking the status of the station, but instead you check the Thread.isInterrupted() flag. Added benefit: I / O and hibernation operations are automatically interrupted. All you have to do is call

 Thread passenger = new Passenger(); passenger.interrupt(); 
+2
source

All Articles