Is an atom nuclear in Java?

I know that increment operation is not atomic in C ++ without blocking.

Will the JVM add lock when iinc ?

+8
java atomic jvm atomicity
source share
6 answers

No its not

  • Get the current value c.
  • Increase the resulting value by 1.
  • Store the incremental value in c.

Java documentation for atomicity and stream interference

You need to either use the synchronized or use the AtomicXXX methods for Thread security.

UPDATE :

 public synchronized void increment() { c++; } 

or

 AtomicInteger integer = new AtomicInteger(1); //somewhere else in code integer.incrementAndGet(); 

Also read: Is iinc atomic in Java?

+17
source share

This is not the case, and it can cause real problems. It is estimated that this test will print 200000000, but this is not due to flow interference

 static int n; public static void main(String[] args) throws InterruptedException { Runnable r = new Runnable() { public void run() { for(int i = 0; i < 100000000; i++) { n++; } } }; Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(n); } 

Please note that volatile does not solve the problem.

+6
source share

{Although there is already an accepted answer, I wanted to clarify something, so a late and technically unnecessary answer}

The answer to your question depends on whether you have an IINC command or what other answers refer to the ++ operator.

Using ++ in a static or instance is nothing but get, increment, and set, so it is not atomic (other answers explain this in more detail).

But

Since you asked if the IINC instruction IINC atomic, this is not a real answer. In fact, none of the answers to this question relate to the instruction, all of them, apparently, are based on the use of the operator in the instance or static fields.


The IINC instruction IINC works with local variables. As the name implies, they are only local and are available only from a very limited volume. Thus, it is not possible to access a local variable from another thread. This means that it does not matter if the instruction is an atom.

+6
source share

No, it is not atomic, the bytecode can alternate with other threads.

+3
source share

i ++ is not atomic in java.
Better to use

 AtomicInteger atomic= new AtomicInteger(1); 

There are methods defined as

 atomic.getAndDecrement(); atomic.getAndIncrement(); atomic.decrementAndGet(); atomic.incrementAndGet(); 

any operation with the above method will be atomic.

This class comes under the java.util.concurrent.atomic package. Java 1.5 added many security features to thready and concurrency flow.

+1
source share

It is not atomic. Here is the generated bytecode for post incrementing the static int:

 0 getstatic 18; // Load value of variable. 3 iconst_1; 4 iadd; 5 putstatic 18; // Store value. 
0
source share

All Articles