File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Can I synchronize a cached object? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Can I synchronize a cached object?" Watch "Can I synchronize a cached object?" New topic
Author

Can I synchronize a cached object?

Raul Quintero
Greenhorn

Joined: Feb 18, 2000
Posts: 7
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

Joined: Nov 02, 2000
Posts: 512
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 ]

By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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 ]
 
 
subject: Can I synchronize a cached object?
 
Threads others viewed
Prepared statement - static variable
Integer int question
Can threads cache writes
Store database in memory or constantly read/write to file?
is it hibernate doing
developer file tools