The first solution is not bad. However, itβs not very dry , 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();
source share