Why doesn't the JVM compile "incrementing an int variable" as an atom operation of Fetch-and-Increment?

I found out that incrementing an int variable in Java is NOT an atomic operation, however I found that processors support atomic operation Fetch-and-Increment.

So my question is: why does the JVM not compile the operation incrementing a int variablefor the atomic Fetch-and-Incrementoperation supported by the CPU, which may be useful in multi-threaded programming.

Early processors had atomic tests and settings, Fetch-and-Incrementor swap commands, sufficient to implement mutexes, which, in turn, could be used to implement more complex parallel objects.

- Java Concurrency in Practice

+4
source share
7 answers

Because the Java Standard (JLS) does not require this and because it is an expensive operation that should only be used when necessary.

+3
source

So my question is why the JVM does not compile the increment of an operation with int variables using the atomic Fetch-and-Increment operation supported by the CPU, which can be useful in multi-threaded programming.

Since on typical modern processors atomic read-modify-write operations (for example, increments) are tens of times more expensive than their corresponding non-atomic operations. And this will not give any advantage - the code cannot rely on atomic operations, because they are not guaranteed to be atomic. So what will be the benefit?

, , ( ):

  • . , . , .

  • ( ), . โ€‹โ€‹ , , , , . ( . .)

, , , Java . , , .

, : . , ( , , , - ). , , MESI. - , .

+3

, : JVM int Fetch-and-Increment, , .

, JVM , , : " , ?"

!=

, , fetch-and-add/inc, , , .

, , , , . , .

, , , , . , , . , .

, , , / . , , .

+3

. , , , , โ€‹โ€‹ RAM- ( ), .

, , ram, op . , /, -, , (512 , , , , ).

, , ( - ) , , , . , , .

0

JVM int variable Fetch-and-Increment, , .

, , volatile. , , , , Java , , . - , . , , , , 99% + , 100% , volatile, .

0

- , , Java, . , Java .

Check answer Why am I ++ not atomic? mentioned by one of the colleagues in the comments

-1
source

Because:

  • Java compilers are not compiled to machine code, they are compiled to bytecode and

  • There is no fetch-and-increment atom instruction in the JVM bytecode, with the exception of local variables.

-1
source

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


All Articles