Is thread safe calling outer class variable?

120 Views Asked by At
public class Status {

    private Scheduler scheduler;
    private volatile Boolean lastResult;

    public Status() {
        scheduler = new Scheduler();
        scheduler.everyTenSeconds(new Action());
    }


    public boolean isSth()  {
        if (lastResult != null && lastResult) {
            return lastResult;
        } else {
            return checkSth();
        }
    }


    private boolean checkSth() throws SomeException {
        // checking sth
    }

    private class Action implements Runnable {

        @Override
        public void run() {
            try {
                lastResult = checkSth();
            } catch (SomeException e) {
                lastResult = false;

            }

        }
    }
}

Is calling outer class variable is thread safe? Last result is lastResult but while calling isSth() lastResult is always null. Despite run was called twice.

1

There are 1 best solutions below

0
On

Is thread safe calling outer class variable?

In general, it is neither thread-safe or not thread-safe. The thread safety depends on what you actually do.

And ... to be strictly correct ... you cannot call a variable:

  • You can read the value of a variable.
  • If the value of the variable is an object, then you can call an instance method of that object.

In your example, the code is doing sequences of operations involving a volatile. A single read or write operation on a volatile is atomic and has clearly defined properties with regards to the Java Memory Model. However, a sequence of operations is NOT atomic, and the JMM properties are complicated.

To cut a long story short, your code is performing sequences of read and write operations on the lastResult and is NOT thread-safe.


However, despite that, I don't see how / why your code is consistently seeing lastResult set to null. I suspect that it is something to do with the way that you are using this code. We really need an MCVE; i.e. a complete and executable example that we can run to see the behavior that you are seeing.