Are primitive datatypes thread-safe in Java
Primitive types are not thread safe. Check this tutorial.
There are three ways in which they're not safe:
long
anddouble
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.