Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a volatile int in Java thread-safe?

Is a volatile int in Java thread-safe? That is, can it be safely read from and written to without locking?

like image 807
shawn Avatar asked Oct 18 '11 09:10

shawn


People also ask

Is volatile int thread safe?

Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.

Is volatile useful for threads?

volatile is unnecessary and useless for synchronization between threads. Threading libraries can't be implemented in terms of volatile ; it has to rely on platform-specific details anyway, and when you rely on those, you no longer need volatile .

Is Java int thread safe?

6) Atomic operations in Java are thread-safe like reading a 32-bit int from memory because it's an atomic operation it can't interleave with other threads.

How do you use volatile in multithreading?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.


1 Answers

Yes, you can read from it and write to it safely - but you can't do anything compound such as incrementing it safely, as that's a read/modify/write cycle. There's also the matter of how it interacts with access to other variables.

The precise nature of volatile is frankly confusing (see the memory model section of the JLS for more details) - I would personally generally use AtomicInteger instead, as a simpler way of making sure I get it right.

like image 59
Jon Skeet Avatar answered Oct 22 '22 12:10

Jon Skeet