Yokupoku Maioku
Yokupoku Maioku

Reputation: 503

differences on syncrhonized block implementations

I would an explanation on these different implmentations:

First:

public void foo(Object key){
    synchronized (map.get(key)) { //-> thread can enter with different key
        int variable = 0;
        for (int j = 0; j <new Random().nextInt(10); j++)
            variable+=j;
        return variable;
    }
}

Second:

public void foo(Object key){
        int variable = 0;
        synchronized (map.get(key)) {      
            for (int j = 0; j < new Random().nextInt(10); j++)
                variable+=j;
            return variable;
        }
    }

Third:

 public void foo(Object key){
    int variable = 0;
    synchronized (map.get(key)) {      
      for (int j = 0; j <new Random().nextInt(10); j++)
       variable+=j;
       lock.lock(); // class instance lock
        try{
        setTheVariable(variable) //-> Example.....
        }finally{
          lock.unlock();
        }
        return variable;
      }
   }

thanks in advance.

Upvotes: 0

Views: 62

Answers (2)

KRiSHNA
KRiSHNA

Reputation: 118

Variables declared inside the foo() method remains attached to the individual threads,because they are local variables. Here you are declaring "j" and "variable" inside the method and those variables will remain attached to the thread executing the method.

Upvotes: 1

KKKCoder
KKKCoder

Reputation: 903

Your first two implementations are the same.

In your third implementation, only one thread can enter the synchronized block, irrespective of whether it is an class instance variable, so the lock is somehow redundant unless your //Do Something Here section has a compelling reason to do so.

Because all the variables involved are local variables, each thread has its own copy of these variables. The returned value of one thread will not be affected by another thread.

However, always watch out for deadlock if two locks are used in this fashion.

Upvotes: 1

Related Questions