简体   繁体   中英

Can I update other object's volatile variable directly?

Say I have an object looks like this.

class Some {

    synchronized void some() {
        // do some with canceled
    }

    synchronized void setAsCanceled() {
        canceled = true;
    }

    volatile boolean canceled = false; // package-private
}

Now another object may update the canceled .

class Other {

    void setSomeAsCanceled() {
        some.canceled = true; // Not calling the setAsCanceled()
    }

    private Some some = new Some();
}

Is it safe to update the canceled volatile variable directly? Or should I call the setAsCanceled() method?

When a variable is created and used, it also exists in a cache. This cache isn't always in sync especially when you are using multiple threads. When you mark a variable as volatile, you are telling the system that the cache has to be updated immediately so that anyone else using it will have the updated value.

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