Exploring the use of streams that impede data race conditions

The following code should prevent the use of data in racing mode using a common synchronization method. But for some reason, the output is always 19915-19980. Shouldn't it be 20,000 if it's not racing data?

public class SyncVarDataRace extends Thread {

    private static int common = 0;

    public void run(){
        synchronized((Integer)common){
            int local = common;
            local+=1;
            common = local;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        SyncVarDataRace[] allThreads = new SyncVarDataRace[20000];

        for(int i = 0; i < allThreads.length; i++){
            allThreads[i] = new SyncVarDataRace();
        }

        for(SyncVarDataRace d: allThreads){
            d.start();
        }

        for(SyncVarDataRace d: allThreads){
            d.join();
        }

        System.out.println(common);
    }
}
+3
source share
1 answer

You are trying to synchronize an object with automatic warping, which will be a different object each time.

synchronized((Integer)common){

The thing is to synchronize the same object in each thread. Even if you did commonbe Integer, once you assign it to a different value, it will be a different object.

. , :

 private final static Object lock = new Object();
 private static int common = 0;
 ...

 synchronized (lock) {
     common++;
 }

, AtomicInteger. - - .

 private static AtomicInteger common = new AtomicInteger(0);
 ...

 // no need to synchronize since that is handled by the class
 common.incrementAndGet();
+5

All Articles