简体   繁体   中英

Thread stopping using volatile variable

Basically if I remove unnecessary stuff I have this code:

public class Foo {
    private volatile boolean isFinished = false;
    private long timeOut = 60 * 1000;
    ...

    // Called asynchronously from another thread
    public setFinished(boolean value) {
        isFinished = value;
    }

    public wait() {
       ...
       long start = SystemClock.uptimeMillis();
       while(!isFinished && (SystemClock.uptimeMillis() - start) <= timeOut) {
           ...
       }

       if (isFinished) {
           // Log success!!!
           ...
       }
       else {
           // Log time out!!!
           ...
       }
    }
}

This code works 95% of the time. The log file is similar to this:

`wait()` is called waiting starts
`setFinished(true)` is called
`setFinished(true)` returns
"success" entry in the log

But sometimes, according to log file the following happens:

`wait()` is called waiting starts
`setFinished(true)` is called
`setFinished(true)` returns
about 60 seconds pass
"time out" entry in the log

Any ideas?

My only guess is that there is something inside these three points which blocks the loop execution:

while(!isFinished && (SystemClock.uptimeMillis() - start) <= timeOut) {
       ...
}

Update: you might also try using System.currentTimeMillis() as uptimeMillis() clock can stop due to changes in environment.

If isFinished only ever transitions from false to true, AND if the while loop has exited, THEN isFinished just has to be true.

This would be the case even if you didn't specify volatile (in practice), and it would definitely be the case given that you specified volatile (both in theory and in practice).

Therefore my guess is that the first assumption is false. If I were you, I'll try this:

// Called asynchronously from another thread
public setFinished(boolean value) {
    if(!value){
        throw new AssertionError("huh?");
    }
    isFinished = value;
}

and see what happens.

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