Atomic Operations and multithreading

后端 未结 6 1333
一整个雨季
一整个雨季 2020-12-13 04:47

Recently I was reading a tutorial, in that I came across a statement that says..

\"The Java language specification guarantees that reading or writing a variable is

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 05:38

    atomicity of an operation is required when you mutate a variable. doing int a = 10; is an atomic operation but its not the one which will give you the problem. the problem giving operations usually are mutating ones like a++ or a = a + 2; and so on.

    Java Specification guarantees that 'reading' and 'writing' are atomic operations not their combinations. so an operation which 'reads, adds 1 and then writes the result back' is not atomic as per specification. such operations are called compound operations and they usually need to be atomic in context of their usage in our code.

    Atomic types help solve this problem. using incrementAndget() on an atomic type makes 'reads, adds 1 and then writes the result back and reads the new result' a single atomic operation in context to thread safety.

    Hope this helps. By the way you should read this (http://walivi.wordpress.com/2013/08/24/concurrency-in-java-a-beginners-introduction/) article about basics of concurrency and threads. it explains such stuff beautifully.

提交回复
热议问题