3

Question comes to my mind while reading about the concurrency issues in threads and dealing with it through synchronized keyword is that,when we use the term lock it is used for the object which contains the run method (or the job of the thread).But why we cannot use the term lock for the method only whose definition contains the synchronized keyword,as this keyword means that once a thread enters the method,then this thread can only be disturbed by the JVM scheduler after the completion of the method?

i am studying from head first java and there is line written over there that the "object is locked" and the reason given is again in a questioning manner that is,"what happen if we have two synchronized method".So i am confuse here that what is the surprising thing that can happen if only the method is locked?

Please forgive me if i asked a vague question and thanks in advance.

OldSchool
  • 2,123
  • 4
  • 23
  • 45
  • You lock on an object, not on a method since that how locks work. Note that it's a lot easier to obtain a reference to an object, and a lot more difficult (and confusing) to obtain one on a method, as the latter would require reflection. Note that this object does **not** need to be the object that contains the `run` method, but can be **any** object that is specified (unless you're using synchronized in a default way), and in fact it is often better **not** to lock on the current object. – Hovercraft Full Of Eels Aug 10 '14 at 20:18
  • @HovercraftFullOfEels i mean to say that the method of the class which implements `runnable` can be used for syn.Please if you can give an explained answer. – OldSchool Aug 10 '14 at 20:22
  • Your question is unclear to me. "A method `run()` can be synchronized." Yes it can, and it works the same way as any other method. Can you show some code that explains exactly what you find confusing? – markspace Aug 10 '14 at 20:33

3 Answers3

8

When synchronizing, an object monitor is acquired by the thread. Since only one thread can acquire the monitor at a time, another thread trying to acquire it will be block. So in a sense nothing is really locked, except maybe a certain piece of code.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • i am studying from head first java and there is line written over there that the "object is locked" and the reason given is again in a questioning manner that is,"what happen if we have two synchronized method".So i am confuse here that what is the surprising thing that can happen if only the method is locked? – OldSchool Aug 10 '14 at 20:17
  • 1
    Well, maybe they want to use a less technical way of putting it. That's what happens anyways, a lot of people think that when "an object is locked" it means it can't be modified. – Kayaman Aug 10 '14 at 20:19
  • So in reality it means that the object which is locked can be modified? – OldSchool Aug 10 '14 at 20:24
  • 2
    Totally. The only thing it prevents is for another thread to acquire the monitor. – Kayaman Aug 10 '14 at 20:40
3

Using synchronized keyword is an implicit equivalent to using a ReentrantLock, as the javadoc shows it in an example :

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

I don't know if it answers to you question maybe I should have juste made a comment.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • please...i dont know much about ReentrantLock,a logical answer about `why` of my question would be appriciated. – OldSchool Aug 10 '14 at 20:13
1

Addressing your question : what happens if we have two synchronized method?
Consider the following code snippet :-

public class Worker {

private Object lock1 = new Object();
private Object lock2 = new Object();

public void step1() {
    synchronized (lock1) {          
        //do something
    }
}

public void step2() {
    synchronized (lock2) {          
        //do something
    }
}

public void process() {
        step1();
        step2();        
}

public void main() {
    long start = System.currentTimeMillis();
    Thread t1 = new Thread(new Runnable() {

        public void run() {
            process();

        }
    });
    t1.start();
    Thread t2 = new Thread(new Runnable() {

        public void run() {
            process();

        }
    });
    t2.start();

        t1.join();
        t2.join();

    long end = System.currentTimeMillis();
    System.out.println("time taken " + (end - start));

}

}

In this code snippet we are using lock1 and lock2 as object locks,but what happens if we use this keyword instead of these locks(lock1 and lock2)?

  • time taken without using this keyword(using lock1,lock2 as in above) = T
  • time taken using this keyword in both synchronized blocks = 2T,

This time difference arises due to the fact that same object lock is used in both the synchronized blocks. If thread-1 would be accessing step1 method, step2 method will be blocked for thread-2. If method are of independent nature, different locks should be used.

Rahul
  • 866
  • 8
  • 19