Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use synchronized

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
shankar vembu
Ranch Hand
Posts: 309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic