简体   繁体   中英

Synchronized (and volatile) not working as expected after screen off/on

I have a class with an instance that is used by two threads. The method called from one thread is:

private Object sync1 = new Object();
private int state;
@Override
protected void onEnabled()  
{
    synchronized (sync1){
        state = getState();
    }
    Log.i(TAG, "onEnabled() " + state );
} 

and from the other:

@Override
public void onF1() {
    int lState;
    synchronized (sync1){
        lState = state;
    }
    Log.i(TAG, "onF1 state " + lState);
}

When starting the app, it works fine, but after turning off/on the screen by pressing the power button, I get the following output in the logcat:

16279-16788 I/MyClass: onEnabled() 1 
16279-16372 I/MyClass: onF1 state 0

The threads are much heavier, and probably they run on different cores of the device. I originally tried to use volatile for the state, and then went to synchronized. Any clues why state is not 1 in onF1 method?

Edit 1: I checked hash on classloader and it is the same before/after. The object address is also the same. I also tried to put a field breakpoint on the variable.

The second thread leaked a reference to the object, so after the turn off/on of the screen, when the Object was recreated, the threads had different instances of the class. With subsequent tests, the address of the object was different for the threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM