Is it synchronized to ensure that the thread sees the last value of the mutable variable modified by another thread?

Here is a simple example:

private long counter = 0;

// note this method is NOT synchronized
// this will be called by thread A
public void increment() { counter++; }

// note this method IS synchronized
// this will be called by thread B
public synchronized long value() { return counter; }

So, I just want to get a good value for counter, rather than a stuck value in the processor cache, because the variable is unstable. The goal is NOT to make the counter volatile so that it does not affect the stream A performing the increments, but only the stream B, which does not bother me when it reads the variable.

For write only, I plan to read the value counterfrom stream B when stream A is already finished ...

+4
source share
4 answers

, B , counter. . , , B, counter , , , A, , .

, , counter volatile . .

: A , B , A B, A , , A . , Thread A, .

+2

long , B , .

. , n n.

AtomicLong .

+2

, synchornized , :

synchornized(this) {
    counter++;
}

( "-" ):

// Thread A
counter++
synchronized (this) {
    finished = true; 
}

// Thread B
synchonized (this) {
    if (finished) {
        // you can read counter here
    }
}

, , counter , , , Thread A (, join()):

threadA.join();
// you can read counter here
+1

. , Thread B . increment() - () - .

, , , .

, . . , , .

0

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


All Articles