Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in synchronization of block

 
mohsin sheikh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Lets take a code:

public abc()
{
List str=new List();
syncronized(str)
{
stmt 1..............
stmt 2..........
more code here....
}
}

My question is that..what is synchronized in above code
1)The List
2)Block of code in syncronized(str)()

Please give me more detail
 
abhishek pendkay
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Block of code in syncronized(str)() is synchronized not the List
and secondly it is synchronized on the List object , which means any thread which wants to execute the block will have to acquire the lock on the List str...
[ April 17, 2008: Message edited by: abhishek pendkay ]
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohsin, please UseCodeTags while posting code. It makes the code easier to read and understand.
mohsin: what is synchronized in above code
1)The List
2)Block of code in syncronized(str)()

It is the block of code:

that is synchronized.

However the code that you have provided does not make any sense because you are synchronizing on an instance that is local to the method abc(). No other thread will ever get a reference to this object and all the threads can concurrently execute the synchronized block.
mohsin: Please give me more detail

  • Synchronization by definition always controls access to a block of code and never an object. (Although, by defining synchronized blocks/methods inside a class you actually control the access to an object but that again is through the controlled access to a block of code! )
  • You always synchronize on an object. This object is often referred to as a monitor.


  • A block of code if synchronized on a monitor M, does not allow more than one threads to enter the block of code at any time that holds the same monitor M.
    [ April 17, 2008: Message edited by: Nitesh Kant ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic