Are primitive datatypes thread-safe in Java

前端 未结 4 780
生来不讨喜
生来不讨喜 2020-11-28 13:38

Are the primitive data types like int & short thread-safe in Java? I have executed the following code and couldn\'t see expected result 500 som

相关标签:
4条回答
  • 2020-11-28 13:40

    I would suggest using classes in java.util.concurrent.atomic. They are designed for thread-safety and in some cases the JVM can take advantage of hardware features to optimize.

    0 讨论(0)
  • 2020-11-28 13:52

    There are three ways in which they're not safe:

    • long and double aren't even guaranteed to be updated atomically (you could see half of a write from a different thread)
    • The memory model doesn't guarantee that you'll see the latest updates from one thread in another thread, without extra memory barriers of some kind
    • The act of incrementing a variable isn't atomic anyway

    Use AtomicInteger etc for thread-safe operations.

    0 讨论(0)
  • 2020-11-28 13:56
    1. To read/write of a value in a multiple thread environment, the program should have proper synchronize or lock to prevent data races. It has nothing to do with which data type to access. In an ideal world, we should share nothing or only share immutable objects, which is always thread safe.

    2. In theory, It is even not ensured to be atomic for long/double according to https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.7 HOWEVER, the implementation tends to atomic, the following code print out nothing with or without volatile keyword in my environment(64bit ubuntu 18.04, Intel 64bit CPU, Oracle JDK 8), so it is atomic in this situation, which I guess apply to all Intel/AMD 64 CPU. We could do the same for double as well, although it is a little tricky to construct double value with certain property to check.

    public class LongThreadSafe {
    
        // multiple threads read and write this value.
        // according to the java spec, only volatile long is guaranteed to be atomic
        private static long value = 0;
    
        private static final int max = (1 << 30) - 1;
        private static final int threadCount = 4;
        static ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    
        static CyclicBarrier barrier = new CyclicBarrier(threadCount);
    
        public static void main(String[] args) throws InterruptedException {
    
            for (int i = 0; i < threadCount; i++) {
                executorService.submit(() -> {
                    try {
                        // all threads start to work at the same time
                        barrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                    for (int j = 1; j < max; j++) {
                        // read value into v2
                        long v2 = value;
                        // check v2 
                        int low = (int) v2;
                        int high = (int) (v2 >> 32);
                        if ((high << 1) != low) {
                            System.out.println("invalid number found high=" + high + ", low=" + low);
                        }
                        // write LongThreadSafe.value again 
                        LongThreadSafe.value = ((long) j << 32) | (long) (j << 1);
    
    
                    }
                });
            }
            executorService.shutdown();
            executorService.awaitTermination(10, TimeUnit.MINUTES);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 13:58

    Primitive types are not thread safe. Check this tutorial.

    0 讨论(0)
提交回复
热议问题