aspose file tools*
The moose likes Threads and Synchronization and the fly likes Doubt in synchronization of block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Doubt in synchronization of block " Watch "Doubt in synchronization of block " New topic
Author

Doubt in synchronization of block

mohsin sheikh
Greenhorn

Joined: Mar 28, 2007
Posts: 22
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

Joined: Jan 01, 2007
Posts: 184
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 ]

The significant problems we face cannot be solved by the same level of thinking which created them – Einstein
SCJP 1.5, SCWCD, SCBCD in the making
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

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 ]

    apigee, a better way to API!
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
     
    subject: Doubt in synchronization of block