apss1943
apss1943

Reputation: 269

synchronized method issue in java

I have three different synchronized methods show below.

A:

 public synchronized static int addCount1() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
        return count;
    }

B:

static void addCount2() {
    synchronized (TestDoubleThread.class) {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }
}

C:

void addCount3(String key) {
    synchronized (myMap.get(key)) {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }
}

All of them can do synchronize as I expect. However, I want to know which one is better, and what is the significant different between all of them. Especially for the case B and case C.

Here is my complete code:

public class TestDoubleThread extends Thread {

    String jobNmae;

    static int count = 0;

    TestDoubleThread(String jobName) {
        this.jobNmae = jobName;
    }

    public static void main(String[] args) throws Exception {

        TestDoubleThread t1 = new TestDoubleThread("A");
        TestDoubleThread t2 = new TestDoubleThread("B");
        t1.start();
        t2.start();

        Thread.sleep(3 * 1000L);
        System.out.println("count=" + TestDoubleThread.count);
    }

    public void run() {
        // addCount2();
        addCount3("A");
    }

    public synchronized static int addCount1() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
        return count;
    }

    static void addCount2() {
        synchronized (TestDoubleThread.class) {
            for (int i = 0; i < 10000; i++) {
                count++;
            }
        }
    }

    void addCount3(String key) {
        synchronized (myMap.get(key)) {
            for (int i = 0; i < 10000; i++) {
                count++;
            }
        }
    }

    public static java.util.Map<String, TestDoubleThread> myMap = new java.util.HashMap<String, TestDoubleThread>();
    static {
        myMap.put("A", new TestDoubleThread("A"));
        myMap.put("B", new TestDoubleThread("B"));
    }
}

Upvotes: 1

Views: 85

Answers (1)

Eran
Eran

Reputation: 393771

addCount2 is synchronized on TestDoubleThread.class while addCount3 is synchronized on the TestDoubleThread instance returned by myMap.get(key). Since you execute it with addCount3("A");, both threads are synchronized on the same object, so one has to wait before the other can execute the method. Therefore it will behave exactly as addCount2, which also synchronizes on the same object.

If, on the other hand, you change it to addCount3(this.jobNmae), each thread would be synchronized on a different object, so both threads will be able to execute addCount3 at the same time, and your count will get screwed.

Upvotes: 4

Related Questions