In java parallel programming, do I need to use a value synchronized while reading?

this class can be used in a multi-threaded thread because it is thread safe.

public class Hello {
    private int value = 0;

    public synchronized int get() {
        return value;
    }

    public synchronized void set(int value) {
        this.value = value;
    }
}

I know that the reason we should use synchronization when get () other than set () is memory visibility.

and the java volatile keyword can be used to make memory visible.

so .. is this class also thread safe ??

public class Hello {
    private volatile int value = 0;

    public int get() {
        return value;
    }

    public synchronized void set(int value) {
        this.value = value;
    }
}
+4
source share
3 answers

. , (, ), , .

. , volatile

  • value

    / value, . Iirc, Java , int int. , , value long, volatile, value

  • value

    , , int. int, , volatile . , , - value++, volatile . Atomic*, synchronized


. , JLS https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7 , volatile / double/long. , 1 .

+2

synchronized get() set, value volatile.

, volatile .

Java, 8.3.1.4. volatile fields:

Java (§17.1). , , , , , , .

Java , , , .

, Java , (§17.4).

, get() set().

+1

Hello int value. , , , AtomicInteger. * . " ", , ", " .

Hello ,

import java.util.concurrent.atomic.AtomicInteger;

public class Hello {
    private AtomicInteger value;

    public int get() {
        return this.value.get();
    }

    public synchronized void set(int value) {
        this.value.set(value);
    }
}

If any object has only one field or its critical updates are limited to only one field of the object, so instead of using synchronization or other thread-safe collections, atomic variables (AtlomicInteger, AtomicReference, etc.).

0
source

All Articles