简体   繁体   中英

What will happen when we create lock (Synchronized block) object inside a method?

public class SampleExecutorService {
    private static int count = 0;

    private void increment() {
        Object lock = new Object();
        synchronized (lock) {
            count++;
        }   
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        SampleExecutorService obj = new SampleExecutorService();
        Runnable task = obj::increment;

        for (int i = 0; i < 1000; i++) {
            executorService.submit(task);

        }
        executorService.shutdown();

        try {
            executorService.awaitTermination(2, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("count : " + count);
    }
}

The expected result for the above program is 1000, but it not gives that result since I followed the synchronization mechanism.But it works fine if we create a lock object in class level instance variable. The right code snippet is below

public class SampleExecutorService {
    private static int count = 0;
    Object lock = new Object();
    private void increment() {
        //Object lock = new Object();
        synchronized (lock) {
            count++;
        }   
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        SampleExecutorService obj = new SampleExecutorService();
        Runnable task = obj::increment;

        for (int i = 0; i < 1000; i++) {
            executorService.submit(task);

        }
        executorService.shutdown();

        try {
            executorService.awaitTermination(2, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("count : " + count);
    }
}

I want know, what will happen when we create lock object inside a method? what is the difference between lock object creation inside a method and as instance variable?

Local variables are stored on thread stack and are created for each thread separately. If the local variable is not a primitive, then the instance itself is stored on the heap, but the reference to object is stored on the thread stack. That's why local variables are thread-safe.

Since the global variables are stored on the heap and are shared/visible by multiple threads they need to be synchronized.

So in your first example you are creating new lock for each thread, so multiple threads are still able to access it.

Here's an excellent article on Java Memory Model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM