0
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.

jnr
  • 121
  • 5
  • 2
    Can you share the example code you're running to produce the problem you describe? – Mick Mnemonic Sep 18 '17 at 12:26
  • Sorry but i didnt understand, are you trying to call thread which has an outer class as variable or thread which has a variable from outer class or calling a thread from outer class – Jeredriq Demas Sep 18 '17 at 12:36

1 Answers1

0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216