Are the primitive data types like int
& short
thread-safe in Java? I have executed the following code and couldn't see expected result 500 some times.
public class SampleThree extends Thread { static long wakeUpTime = System.currentTimeMillis() + (1000*20); static int inT; public static void main(String args[]) { System.out.println("initial:" + inT); for(int i=0; i<500; i++) new SampleThree().start(); try { Thread.sleep(wakeUpTime - System.currentTimeMillis() + (1000*30)); System.out.println("o/p:" + inT); } catch(Exception e){ e.printStackTrace(); } } public void run() { try { long s = wakeUpTime - System.currentTimeMillis(); System.out.println("will sleep ms: " + s); Thread.sleep(s); inT++; // System.out.println(inT); } catch(Exception e) { e.printStackTrace(); } } }
Here concurrently 500 thread will update the int variable inT
. Main thread after waiting for concurrent update to be completed, prints inT
value.
Find similar example here
When designing a class that may be used for concurrent programming—that is, a class whose instances may be used by more than one thread at a time—it is imperative that you make sure the class is " thread-safe.” Consider the IntList class of Example 2-7. This class is not thread safe.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
So point is, in Java, long and double aren't thread safe. When multiple threads are going to access a long or a double value without synchronization, it can cause problems. To ensure atomic/thread safety, it is essential to use volatile to ensure changes made by one thread are visible to other threads.
A string is immutable and therefore thread safe.
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)Use AtomicInteger
etc for thread-safe operations.
Primitive types are not thread safe. Check this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With