• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized block and synchronized method

 
pete reisinger
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I just want to make sure that I understand this.

synchronized method is the same as synchronized block on "this":

same as

synchronized just crates lock on the supplied object, and makes sure that the block is executed only by one thread (but of course if we have two instances it wouldn't work, because lock is on "this" instance.

so I would use synchronized block if I get object from a class I don't have access to. For example:

I inherited method getSth() which returns object, but I don't have access (cannot modify) to the class I inherit from, so I cannot change method getSth() to synchronized.
but now I have to make sure that all my classes that inherit from that class, put the "getSth()" in the synchronized block.

so in this case the block checks if any other thread is using the object returned by getSth(), if so, it waits till the thread finishes and after that starts the execution of the method. (this is valid only if the thread used object which have synchronized block, if it didn't then our thread can execute methods on this object simultaneously, because the previous thread didn't use any lock).

basically synchronized just creates/uses lock on the supplied argument, so if we use synchronized block for example on car object, we have to make sure that all our threads will have access to the car object through synchronized block (at least the methods we want to be synchronized), because it will check if there's any lock and if it is in use.

I'm not sure if I explained it well, but this is my understanding, so please let me know if it's correct.
Thanks
 
Ajay Saxena
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pete reisinger wrote:
synchronized method is the same as synchronized block on "this":


That's correct as as long as you don't have any logic outside the synchronized block in the enclosing method.


Also,your requirement is not quite clear. Are you trying to synchronize access to the object returned by getSth()? Can you elaborate your requirement in detail.
May be you can share the source code and state your requirements.
 
pete reisinger
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
thanks for the answer. I don't have any source code, I was asking this because I knew synchronized methods, but
wasn't sure about synchronized block (the example is made up). So I just wanted to make sure that I understand it.
Thanks again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!