1 2 Previous Next 15 Replies Latest reply: Jun 15, 2008 10:15 AM by 796440 RSS

    howto call two 'synchronized' methods simultaneously from a single class?

    807591
      Hi,

      I am new to Java programming and having some query regarding use of 'synchrnoized' methods in a class. From documentation I have following information:

      1. two differrent threads can call one 'synchronized' method and another non-synchronized method of the same class.

      class A{
      public synchronized void display(){}
      public void update(){}
      }

      2. two differrent threads cannot call two 'synchronized' methods of the same class. For example, following class has two 'synchronized' methods and only one thread can call any one of the methods at a time.

      class A{
      public synchronized void display(){}
      public synchronized void update(){}
      }

      My question is 'Is there any technique that will allow simultaneous access for two threads on two different 'synchrnoized' methods?
      Does 'Semaphore' help this issue?

      Thanking your immediate valuable response.
      Regards/Sim
        • 1. Re: howto call two 'synchronized' methods simultaneously from a single clas
          807591
          The threads can access those methods simultaneously. The synchronized modifier doesn't apply on the instance, which you seem to think, but on the methods.

          Having said that, you're new to Java and you're worrying about concurrency right now. Something says me that you've a misunderstanding about it and are looking for solutions in the wrong direction. If you elaborate the actual problem in detail, then we might point you the right approach out.
          • 2. Re: howto call two 'synchronized' methods simultaneously from a single clas
            807591
            I'm just learning this, so I welcome corrections, but what if you didn't synchronize on the methods but on blocks inside the methods and use different objects to hold the synch keys for the two different blocks?
            • 3. Re: howto call two 'synchronized' methods simultaneously from a single clas
              807591
              Hi,

              If I am not wrong 'synchronization' applies on the instance level. If not, why the whole object gets locked when a synchronized method of an object is being called by a thread? I came across this question while trying to see the actual usage of 'Semaphore' class in java. It says concurrent sharing of an object is possible using Semaphores. So I thought of making a re-thinking that if sharing is available using 'Semaphore' my question could get solved. But still wanted a clear comment from you all guys.

              btw, learning 'synchronization' is nothing wrong for a new java guy. It's newcomers who should learn this than expers like you :)

              Thanks/Sim
              • 4. Re: howto call two 'synchronized' methods simultaneously from a single clas
                807591
                I have to correct myself about the lock, but still, what problem do you have with your application with which you think to solve with synchronization? Do you for example have declared static variables which shouldn't be static at all?
                • 5. Re: howto call two 'synchronized' methods simultaneously from a single clas
                  807591
                  Here's an example of what I meant by method vs block synchronization:
                  public class SynchTest
                  {
                  
                    Object obj1 = new Object();
                    Object obj2 = new Object();
                  
                    public synchronized void display()
                    {
                      try
                      {
                        System.out.println("start display");
                        Thread.sleep(2000);
                        System.out.println("end display");
                      }
                      catch (InterruptedException e)
                      {
                        e.printStackTrace();
                      }
                    }
                  
                    public synchronized void update()
                    {
                      try
                      {
                        System.out.println("start update");
                        Thread.sleep(2000);
                        System.out.println("end update");
                      }
                      catch (InterruptedException e)
                      {
                        e.printStackTrace();
                      }
                    }
                  
                    public void internalSynch1()
                    {
                      synchronized (obj1)
                      {
                        try
                        {
                          System.out.println("start internalSych1");
                          Thread.sleep(2000);
                          System.out.println("end internalSych1");
                        }
                        catch (InterruptedException e)
                        {
                          e.printStackTrace();
                        }
                      }
                    }
                  
                    public void internalSynch2()
                    {
                      synchronized (obj2)
                      {
                        try
                        {
                          System.out.println("start internalSych2");
                          Thread.sleep(2000);
                          System.out.println("end internalSych2");
                        }
                        catch (InterruptedException e)
                        {
                          e.printStackTrace();
                        }
                      }
                    }
                  
                    public static void main(String[] args)
                    {
                      System.out.println("Synchronized methods test:");
                      
                      final SynchTest synchtest = new SynchTest();
                      new Thread(new Runnable()
                      {
                        public void run()
                        {
                          synchtest.display();
                        }
                      }).start();
                      new Thread(new Runnable()
                      {
                        public void run()
                        {
                          synchtest.update();
                        }
                      }).start();
                      
                      try
                      {
                        Thread.sleep(4500);
                      }
                      catch (InterruptedException e)
                      {
                        e.printStackTrace();
                      }
                      System.out.println();
                      System.out.println("Synchronized blocks test:");
                      
                      new Thread(new Runnable()
                      {
                        public void run()
                        {
                          synchtest.internalSynch1();
                        }
                      }).start();
                      new Thread(new Runnable()
                      {
                        public void run()
                        {
                          synchtest.internalSynch2();
                        }
                      }).start();
                    }
                  
                  }
                  • 6. Re: howto call two 'synchronized' methods simultaneously from a single clas
                    807591
                    Hi,
                    Good work! Thanks for the prompt response and now I understand the possibility of running multiple methods but with synchronized blocks.

                    Regard/Sim
                    • 7. Re: howto call two 'synchronized' methods simultaneously from a single clas
                      807591
                      simlim wrote:
                      Good work! Thanks for the prompt response and now I understand the possibility of running multiple methods but with synchronized blocks.
                      You're welcome, but please mind my caveat above. I'm very much a neophyte at this, so don't take anything I say in this matter as gospel, and in fact it is far from it.
                      • 8. Re: howto call two 'synchronized' methods simultaneously from a single clas
                        baftos
                        Just want to add something. Synchronized methods are just syntactic sugar.
                        You should concentrate on synchronized blocks, which are the basic construct.
                        synchronized void MyMethod()
                        {
                          ...
                        }
                        is exactly the same as
                        void MyMethod()
                        {
                          synchronized ( this )
                          {
                            ...
                          }
                        }
                        static synchronized void MyMethod()
                        {
                          ...
                        }
                        is exactly the same as
                        static void MyMethod()
                        {
                          synchronized ( TheClassContainingMyMethod.class )
                          {
                            ...
                          }
                        }
                        Another point that OP may want to study later.
                        Two synchronized blocks using the same synchronization object obj can
                        be executing in the same time if one of them calls obj.wait() inside the synchronized(obj)
                        block.
                        .
                        • 9. Re: howto call two 'synchronized' methods simultaneously from a single class?
                          796440
                          simlim wrote:
                          2. two differrent threads cannot call two 'synchronized' methods of the same class. For example, following class has two 'synchronized' methods and only one thread can call any one of the methods at a time.

                          class A{
                          public synchronized void display(){}
                          public synchronized void update(){}
                          }
                          On the same object, yes. But each object has its own lock, so T1 can call either method on a1 concurrently with T2 calling either method on o2.
                          My question is 'Is there any technique that will allow simultaneous access for two threads on two different 'synchrnoized' methods?
                          Call them on two different objects. But why do you think you need to do this?
                          • 10. Re: howto call two 'synchronized' methods simultaneously from a single clas
                            796440
                            Encephalopathic wrote:
                            Here's an example of what I meant by method vs block synchronization:
                            Method syncing is the same as block syncing. In method syncing, the lock is the object (non-static method) or the Class object (static method) and the block is the entire method body.
                            • 11. Re: howto call two 'synchronized' methods simultaneously from a single clas
                              807591
                              thanks baftos and jverd for clearing this up for me.
                              • 12. Re: howto call two 'synchronized' methods simultaneously from a single clas
                                807591
                                thanks for the info. Howabout the following scenario? Does both of them execute simultaneously or one by one?

                                void MyMethod1()
                                {
                                synchronized ( this )
                                {
                                ...
                                }
                                }

                                static synchronized void MyMethod2()
                                {
                                ...
                                }

                                At the above, one is class-level method [MyMethod()] and the other is instance level method[void MyMethod()]. When run, will two threads be able to run the above two methods simultaneously? This is to clear the point that "class-level" lock is different from "object-level" lock. Are there two different locks or there is only one single level be it class level or instance level.

                                To summarise, I would write as follows:

                                1. There are two types of locks- class-level and object-level. Does it mean there two different locks at the same time or only one lock but two types- ie, it can be either class-level or object-level but not both at the same time.
                                2. Does it mean that two different threads can invoke methods inside the class simultaneously? In our case Thread T1 invokes 'void MyMethod1()' and Thread T2 invokes 'static synchronized void MyMethod2()' ?

                                Thanking you for your valuable comments. / Sim.
                                • 13. Re: howto call two 'synchronized' methods simultaneously from a single clas
                                  807591
                                  Re: class-level lock and object-level lock.

                                  I have run the following two programmes:

                                  1. Programme1 - withouth 'static' modifier:
                                  -------------------------------------------------------------
                                  public class SynchTest {

                                       public synchronized void display() {
                                            try {
                                                 System.out.println("start display");
                                                 Thread.sleep(2000);
                                                 System.out.println("end display");
                                            } catch (InterruptedException e) {
                                                 e.printStackTrace();
                                            }
                                       }

                                       public synchronized void update() {
                                            try {
                                                 System.out.println("start update");
                                                 Thread.sleep(2000);
                                                 System.out.println("end update");
                                            } catch (InterruptedException e) {
                                                 e.printStackTrace();
                                            }
                                       }

                                       public static void main(String[] args) {
                                            System.out.println("Synchronized methods test:");

                                            final SynchTest synchtest = new SynchTest();
                                            new Thread(new Runnable() {
                                                 public void run() {
                                                      synchtest.display();
                                                 }
                                            }).start();
                                            new Thread(new Runnable() {
                                                 public void run() {
                                                      synchtest.update();
                                                 }
                                            }).start();
                                       }
                                  }

                                  Output:
                                  -----------
                                  Synchronized methods test:
                                  start display
                                  end display
                                  start update
                                  end update

                                  2. Programme2 - with 'static' modifier:
                                  -------------------------------------------------------------
                                  public class SynchTest {

                                       public synchronized void display() {
                                            try {
                                                 System.out.println("start display");
                                                 Thread.sleep(2000);
                                                 System.out.println("end display");
                                            } catch (InterruptedException e) {
                                                 e.printStackTrace();
                                            }
                                       }

                                       public static synchronized void update() {
                                            try {
                                                 System.out.println("start update");
                                                 Thread.sleep(2000);
                                                 System.out.println("end update");
                                            } catch (InterruptedException e) {
                                                 e.printStackTrace();
                                            }
                                       }

                                       public static void main(String[] args) {
                                            System.out.println("Synchronized methods test:");

                                            final SynchTest synchtest = new SynchTest();
                                            new Thread(new Runnable() {
                                                 public void run() {
                                                      synchtest.display();
                                                 }
                                            }).start();
                                            new Thread(new Runnable() {
                                                 public void run() {
                                                      synchtest.update();
                                                 }
                                            }).start();
                                       }
                                  }

                                  Output:
                                  -----------
                                  Synchronized methods test:
                                  start display
                                  start update
                                  end display
                                  end update

                                  From the above output, 'start update' runs before completion of first method. Does it mean object-level lock and class-level locks are different and two threads can independently access both methods simultaneously?

                                  Thanks / Sim
                                  • 14. Re: howto call two 'synchronized' methods simultaneously from a single clas
                                    796440
                                    simlim wrote:
                                    thanks for the info. Howabout the following scenario? Does both of them execute simultaneously or one by one?
                                    The answer is already provided in the above posts.
                                    At the above, one is class-level method [MyMethod()] and the other is instance level method[void MyMethod()]. When run, will two threads be able to run the above two methods simultaneously? This is to clear the point that "class-level" lock is different from "object-level" lock. Are there two different locks or there is only one single level be it class level or instance level.
                                    The answer is already provided in the above posts. Note, however, that there are no such things as "class-level" and "object-level" locks. There are just locks, and each lock is associated with exactly one object.
                                    1. There are two types of locks- class-level and object-level.
                                    Incorrect.
                                    2. Does it mean that two different threads can invoke methods inside the class simultaneously?
                                    The answer is already provided in the above posts.
                                    1 2 Previous Next