Results 1 to 2 of 2
  1. #1
    guest_user is offline Member
    Join Date
    May 2011
    Posts
    47
    Rep Power
    0

    Question Qns on synchronized methods

    Would anything go wrong if a call is made to a synchronized method that calls another if its own object's synchronized method? since the calling thread would make 2 requests for the monitor lock of the same object?

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,431
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by guest_user View Post
    Would anything go wrong if a call is made to a synchronized method that calls another if its own object's synchronized method? since the calling thread would make 2 requests for the monitor lock of the same object?
    If I understand your question correctly, the following is an example:

    Java Code:
    public class Test {
       public synchronized void foo() { bar(); }
       public synchronized void bar() { ... }
    }
    foo() calls bar() and both methods synchronize on the same Test object. Does this depict your question? If yes, nothing goes wrong here because those locks are 'counted' i.e. if you already own the lock on an object, you can lock it again. You have to unlock it as many times as you locked it but this goes automatically through the unwinding of the method stack, i.e. if bar() returns the lock counter is decremented and it is decremented once more when foo() returns.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Problems with synchronized
    By BigHotCuppa in forum Threads and Synchronization
    Replies: 3
    Last Post: 11-20-2010, 08:11 PM
  2. Replies: 1
    Last Post: 09-08-2010, 04:08 PM
  3. Synchronized(this)?
    By kiza in forum Threads and Synchronization
    Replies: 10
    Last Post: 04-07-2009, 01:20 PM
  4. Replies: 3
    Last Post: 10-06-2008, 12:27 AM
  5. synchronized
    By bugger in forum New To Java
    Replies: 2
    Last Post: 11-28-2007, 10:33 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •