Is the pre-increment operator thread-safe?

江枫思渺然 提交于 2019-11-27 15:00:42

No, you should be using something like java.util.concurrent.atomic.AtomicInteger. Look at its getAndIncrement() method.

Pre-increment on int is not thread safe, use AtomicInteger which is lock-free:

AtomicInteger carsComplete = new AtomicInteger();

//...

switch(carsComplete.incrementAndGet())

BTW the code below is not thread safe as well. Can you tell why?

carsComplete.incrementAndGet();
switch(carsComplete.get())

++ operator is not atomic. Look at here http://madbean.com/2003/mb2003-44/. For atomic operations you can use AtomicInteger

AtomicInteger atomicInteger = new java.util.concurrent.atomic.AtomicInteger(0)

and every time you want to increment you can call atomicInteger.incrementAndGet() method which returns a primitive int. 0 is the default initial value for the atomic integer.

Same as in C++ the operator ++ is not atomic.

It is actually more than 1 instruction being executed under the hood (don't be fooled by seeing just a simple ++i; it is load/add/store) and since there is more than 1 instruction involved without synchronization you may have various interleavings with wrong results.

If you need to incrent the carsComplete in a thread-safe manner you can use java's construct AtomicInteger or you could synchronize the whole method

Question is “is pre increment operator thread safe ?”

Ans : No , Why ? because of number of instructions involved. Atomic means single operation , here load/add/store operations need to be performed. So not an atomic operation.

  Same for post increment.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!