Is the getter method an alternative to volatility in Java?

I am wondering if the getter method for a private boolean field causes other threads to get the latest updated value? Is this an alternative for a volatile field? For instance:

Class A {
    private boolean flag;

    public boolean getFlag() {
        return this.flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

against

Class B {
    public volatile boolean flag;
}

Edit: Is it true that the whole object is cached by the stream (including the private field), so when I call getter it will return the cached private field?

+4
source share
3 answers

No, getter will not cause field synchronization.

when it comes to reading and writing a primitive in a multi-threaded environment, we have three problems caused by the processor

  • : , , 64- 32- . .
  • : , , , . , .
  • : , .

Getter . , JIT . ?

Volatile - . . , , . , , .

, , . : " , flag, ?" , , . , , , ( ) , . , . JIT ", ". .

: , ( ), , , ?

. JVM, . . , , , ? ?

+3

, getter

. volatile.

?

. getter- boolean volatile.

: AtomicBoolean

, . . java.util.concurrent.atomic .

:

-

//?

+1

? ?

, getter , volatile, , , .

You need to know the following text here and clearly understand the concept of atomic access.

The volatile variable is always visible to other threads . It also means that when a stream reads a volatile variable, it just does not see the last change in volatile

0
source

Source: https://habr.com/ru/post/1674367/


All Articles