• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can I synchronize a cached object?  RSS feed

 
Raul Quintero
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all!
I have an object that I recieve via JMS. I store that object in a HashTable. When a certain event happens, I run that cached object. Can I synchronize the object when I put it into the cache, there by making it always synchronized, or do I have to synchronize the object after I get it out of the cache and perform my method call?
If this is confusing, please let me know and I'll try to clarify.
Thanks.
 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you can synchronize your object. Just put the synchronized keyword before the method in your object that is accessing it or changing it and only one thread can run that code at a time.
-Dale
[ February 07, 2002: Message edited by: Dale DeMott ]
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by "synchronize the object"?
Let me explain by confusing you first Although it is common to talk about a "synchronized object", you could argue that there is actually no such thing. Objects aren't really synchronized. Operations are.
That, I guess, is why a lot of developers get into trouble when they use the synchronized collection classes like Hashtable (don't use that - use Collections.synchronizedMap(new HashMap()) if you must). They take a threadsafe Map, then start writing their code against it thinking it'll be threadsafe because the underlying Map "is threadsafe". It won't be. Your code is essentially defining new, more complicated operations on the Map that are probably not threadsafe at all.
So to rephrase my question: "What operations do you think need synchronizing (and why)"?
- Peter
PS. For one interpretation of "making an object synchronized", see the source for Collections.synchronizedCollection(Collection) and friends.
[ February 08, 2002: Message edited by: Peter den Haan ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!