Problematic Code :
package com.demo.atomicDemo; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class NonAtomicDemo { public static void main(String[] args) throws InterruptedException { ExecutorService executerService = null; Counter count = new Counter(); executerService = Executors.newFixedThreadPool(2); Runnable task1 = () -> { for(int i=0;i<2000000;i++) { count.incremenetCounter(); // System.out.println(Thread.currentThread().getName()+" ---- "+count.getCounter()); } }; Runnable task2 = () -> { for(int i=0;i<8000000;i++) { count.incremenetCounter(); // System.out.println(Thread.currentThread().getName()+" ---- "+count.getCounter()); } }; executerService.submit(task1); executerService.submit(task2); executerService.awaitTermination(1, TimeUnit.SECONDS); executerService.shutdown(); System.out.println(count.getCounter()); } } class Counter{ private int counter; public int getCounter() { return counter; } public void incremenetCounter() { counter = counter+1; } }
Ouptut
Fixing the code by using volatile and synchronized but it is slow
class Counter{ private volatile int counter; public int getCounter() { return counter; } public synchronized void incremenetCounter() { counter = counter+1; } }
Why synchronized is slow you ask ?
- Because to enter into the synchronized block between threads there has to be a lot of context switching