Little synchronization question...
A question for concurrency experts....
Is it fair to assume that the following is NOT Thread-safe (assuming 'o' will not be modified after the call but of course different instances of 'o' may be passed when the method is called by Thread instances):
publicvoid doSomething(Object o){
lock.lock();
try{
o.change();
}finally{
lock.unlock();
}
}
My concern really is whether when the method is called from different threads with different instances of 'o', that the try{} block may see 'o' in an indeterminate / incomplete state. Is this true?
Cheers
Lance
[934 byte] By [
LanceJa] at [2007-11-27 2:29:46]

My concern really is whether when the method is called from different threads with different instances of 'o', that the try{} block may see 'o' in an indeterminate / incomplete state. Is this true?
Yes.
the method, doSomething() is itself thread safe. But the o.change() is irrelevant since the object "o" may be instantiated/changed elsewhere. Unless the change() method is the ONLY method that can change the object.
This is really nasty code. Someone looking at it cannot be sure just what is going on. Instead of using Lock, just synchronize on the Object. At least this way people can easily understand what is happening.
> A question for concurrency experts....
>
> Is it fair to assume that the following is NOT
> Thread-safe (assuming 'o' will not be modified after
> the call but of course different instances of 'o' may
> be passed when the method is called by Thread
> instances):
>
> > public void doSomething(Object o) {
>lock.lock();
> try {
> o.change();
> nally {
> lock.unlock();
>
>
>
> My concern really is whether when the method is
> called from different threads with different
> instances of 'o', that the try{} block may see 'o' in
> an indeterminate / incomplete state. Is this true?
>
> Cheers
> Lance
The method is thread safe provided the o is immutable, and there are some conditions which need to met for being immutable.
All the members are final
you cannot change the state of the object
there are no setter methods.
if thats not the case its not thread safe.
Secondly what do you mean by lock?
Thanks very much for the responses. A better example hopefully:
List<Object> list = Collections.synchronizedList(new ArrayList<Object>());
public void doSomething(Object o) { // o is immutable
list.add(o); // list inherently sync'd
}
Now let's say I have multiple threads rapidly calling this method with immutable instances of 'o'. Can it occur that while the statement list.add(o) is executing that 'o' is replaced with a new instance of 'o' (from another calling Thread) and therefore the add() method sees 'o' in indeterminate state?
In other words, do I also need to do
List<Object> list = Collections.synchronizedList(new ArrayList<Object>());
public synchronized void doSomething(Object o) { // o is immutable
list.add(o); // list inherently sync'd
}
to guarantee absolute Thread safety?
thanks again
Lance