In Java, we often use primitive datatypes like short, int, long, float, double, boolean etc. Are these java primitive data types atomic, reliable, threadsafe in multi threaded programming ?
This blog post tries to examine the thread safety of such primitive data types.
Let us first start with a simple testing on primitive data type 'integer'.
I've created 200 threads and set them to attack on 'integer' variable 'anInteger' to test it's stability to hold the value on concurrent thread manipulations.
Solution:
Use concurrent package classes.
AtomicInteger
Similar questions,
Are primitive types in java thread safe ?
Is primitive data types in java designed to be atomic in concurrent access paradigm ?
This blog post tries to examine the thread safety of such primitive data types.
Let us first start with a simple testing on primitive data type 'integer'.
I've created 200 threads and set them to attack on 'integer' variable 'anInteger' to test it's stability to hold the value on concurrent thread manipulations.
public class Test extends Thread{ static int anInteger = 0; // initialize static final long START_TIME = System.currentTimeMillis() + (1000 * 5); // 20 seconds from current time. public static void main(String[] args) throws Exception { // employ 200 threads. for(int i=0; i<200; i++) { new Test().start(); } // wait for some time so all 200 threads completes its execution. Thread.sleep(1000*20); System.out.println(anInteger); // We EXPECT TO PRINT 200. but it prints some corrupted integer value !! } public void run() { try { Thread.sleep(START_TIME - System.currentTimeMillis()); } catch(InterruptedException e) { e.printStackTrace(); } anInteger += 1; } }
The expected output 200 is not printed !!
This proves ourself that primitive datatypes are not threadsafe in java !!
Use concurrent package classes.
AtomicInteger
Similar questions,
Are primitive types in java thread safe ?
Is primitive data types in java designed to be atomic in concurrent access paradigm ?