I have a simple class that does some calculations in its thread and reports the results to the listener.
class Calculator extends Thread {
protected Listener listener;
public void setListener(Listener l) {
listener = l;
}
public void run() {
while (running) {
... do something ...
Listener l = listener;
if (l != null) {
l.onEvent(...);
}
}
}
}
At any time, the user can call setListener (null) if he does not want any events for a certain period of time. Thus, in the run () function, I create a copy of the listener, so I cannot throw a NullPointerException that can occur if the listener is set to null after the status = = null check is successful. In my case, I think this is the right alternative for synchronization.
: - ? volatile, , , (boolean, int,...), . , / . , , -, .
!