Re: Collections and Decorators
ankur wrote:
So Lew can I always use synchronized(c) and rest assured that my
operations on the collection would not be thread safe.
I'm having a hard time endorsing the association of "rest assured" with "not
.... safe".
Regardless, the answer is no.
Remember the part of my message that said
It isn't a question of can you do that,
it's a question of when should you do that.
There are multiple synchronization strategies.
The use of 'Collections.synchronizedX()' only
synchronizes most of the public method calls;
it doesn't resolve every possible synchronization
issue, nor is it the only way to synchronize the collection.
Proper concurrency-aware programming is one of the Dark Arts.
?
ankur wrote:
I meant, can I avoid using Collections.synchronizedCollection(c) by using an
Why do you wish to avoid it?
equivalent code block that just uses synchronized(c) construct.
Under what circumstances does that give you an advantage?
What advantage?
What dangers or other collateral impact does it have?
Can you please give me an example where I will have to necessarily use
Collections.synchronizedCollection(c) and I will not be able to get by
just using
synchronized(c)
{
}
"just" using?
What do you see as the differences, pro and con, in your analysis?
Remember,
There are multiple synchronization strategies.
For example, suppose what you need is a concurrent HashMap. You could:
Map <Foo, Bar> associations = new HashMap <Foo, Bar> ();
Map <Foo, Bar> synchAssns = Collections.synchronizedMap( associations );
Map <Foo, Bar> concurrences = new ConcurrentHashMap <Foo, Bar> ();
....
public Bar get( Foo foo )
{
synchronized( associations ) { return associations.get( foo ); }
}
public Bar getSynch( Foo foo )
{
return synchAssns.get( foo );
}
public Bar getConcur( Foo foo )
{
return concurrences.get( foo ); }
}
There really is no one-size-fits-all for every concurrency situation. You
have to think very carefully about your particular scenario.
Please do not quote sigs.