Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes When to use synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When to use synchronized" Watch "When to use synchronized" New topic
Author

When to use synchronized

Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
Okay.. so I'm going over some code... and I see the previous people have used synchronized here and there. They did not use the synchronized key word on anything that is a singleton nor did they use any of this code on any database writes. When else might be a good time to use the synchronized keyword?


By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
shankar vembu
Ranch Hand

Joined: May 10, 2001
Posts: 309
well, i make my static methods synchronized because they might access static class variables.... of course, this I do only if my environment is multi-threaded, for example a web-application.
regards.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
When else might be a good time to use the synchronized keyword?
Ummm, any time you've got mutable data that is accessible by more than one thread. Any Java book that talks about threads should have a section on this. I recommend Effective Java in particular. Pages 189-195 discuss when to synchronize; the rest of the book is realy useful for other stuff.
They did not use the synchronized key word on anything that is a singleton
That sounds a bit suspicous to me. If anything, the fact that an instance is a singleton probably increases the chance that more than one thread will access it, which usually will require synchronization. I suspect that if this class doesn't use synchronization, it's because it's not actually designed to be thread-safe. If it's not used in a multi-threaded environment (or more accurately, not used by more than one thread) then that's fine. Most classes aren't thread-safe after all. But don't think that the fact that it's a singleton is what protects it.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use synchronized