Atomic Operations and multithreading

后端 未结 6 1331
一整个雨季
一整个雨季 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:37

    You use int or long based on the upper/lower limit on the range of numbers you are dealing with. Please do not mix non-atomic behavior of long with AtomicLong. Whatever you have written above is correct but you are probably mixing both concepts. AtomicXXX are more useful in cases where you are doing "compare & set" kind of operations. For example even when int can be modified/read atomically following code will be incorrect in multithreaded environment :

    int i =10
    ..
    ..
    ..
    if(i == 10) i++;
    

    in multithread environment two threads can access this code atomically and updated value of i and making it come in consistent state. SO deal with such situations normally you guard the code "if(i == 10) i++;" with synchronized block. However AtomicInteger class provides the API to achieve such things without using synchronized blocks which are slower. Same is the case of AtmoicLong APIs

提交回复
热议问题