Java Should I declare a member variable of my common listener as mutable?

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,...), . , / . , , -, .

!

+5
2

. , Calculator , , .

volatile . java.util.concurrent.AtomicReference , , , .

+5

, , setListener(null). :

Listener l = listener; // listener != null at this point

// setListener(null) executes here

if (l != null) {
    l.onEvent(...);
}

, , , . listener volatile . :

public synchronized void setListener(Listener l) {
    listener = l;
}

public void run() {
    while (running) {
        ... do something ...

        synchronized (this) {
            if (listener != null) {
                listener.onEvent(...);
            }
        }
    }
}

synchronized , :

if (listener != null) {
    synchronized (this) {
        if (listener != null) {
            listener.onEvent(...);
        }
    }
}

, . listener volatile, , .

+3

All Articles