dcsimg
Does synchronized methods lock the whole object or just the method?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Michael_Couck
Posted On:   Friday, December 5, 2003 06:34 AM

Hi, My understanding is that if you synchronize a method, the whole object gets locked, due to the implied lock on the "this" object, it's self. And if you lock a block of code the lock is only on the block, i.e. other methods can be accessed by another thread. Is this right? Here is an example: 1) public class Data { public synchronized lock(int recNo) { //The Data class is locked for the //duration of this method } } 2) public class Data { public lock(int recNo) { synchronized(object) { //Only this block is locked, //othe   More>>

Hi,





My understanding is that if you synchronize a method,
the whole object gets locked, due to the implied lock
on the "this" object, it's self. And if you lock a
block of code the lock is only on the block, i.e. other
methods can be accessed by another thread. Is this
right?

Here is an example:

1)

			
public class Data {
public synchronized lock(int recNo) {
//The Data class is locked for the
//duration of this method
}
}


2)

			
public class Data {
public lock(int recNo) {
synchronized(object) {
//Only this block is locked,
//other methods can be enntered
//by other threads
}
}
}


My problem is that the SCJD project requires a lock on
a record, which is not normally a problem, but the
interface that is required to be implemented is really
ugly and by that it is necessary to lock all the
records from the method level, thereby rendering any
locking mechanism redundant. I have tried to link the
interface into the locking mechanism without rendering
the locking mechanism it's self redundant without
sucess. If on the other hand methods locked at the
method level (example 1 above) do NOT lock the entire
object then there would indeed be benefit to the
locking. So the question is, if a method is
synchronized at the method level as in example "1"
above, does this lock the entire object? And if a block
is synchronized inside a method is there access to
other methods by other threads.



Thanks

Michael    <<Less

Re: Does synchronized methods lock the whole object or just the method?

Posted By:   Edy_Salim  
Posted On:   Monday, December 8, 2003 12:15 AM

Hi,


Example 1)


public class Data {
public synchronized lock(int recNo) {
//The Data class is locked for the
//duration of this method
}
}

In your example above, it is the instance of Data that will be locked. Every object has lock and the lock is controlled by at most one single thread.


Example 2)


public class Data {
public lock(int recNo) {
synchronized(object) {
//Only this block is locked,
//other methods can be enntered
//by other threads
}
}
}

In your example above, it is the object that passed to synchronized statement is going to be locked. It has nothing to do with the Data class or its instances.


Edy Salim

About | Sitemap | Contact