Are primitive datatypes thread-safe in Java

穿精又带淫゛_ 提交于 2019-11-27 04:45:13

There are three ways in which they're not safe:

  • long and double aren't even guaranteed to be updated atomically (you could see half of a write from a different thread)
  • The memory model doesn't guarantee that you'll see the latest updates from one thread in another thread, without extra memory barriers of some kind
  • The act of incrementing a variable isn't atomic anyway

Use AtomicInteger etc for thread-safe operations.

Parvin Gasimzade

Primitive types are not thread safe. Check this tutorial.

I would suggest using classes in java.util.concurrent.atomic. They are designed for thread-safety and in some cases the JVM can take advantage of hardware features to optimize.

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