• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When to use synchronized

 
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 309
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic