• 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

synchronization problem: Please help me

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Friends,
I was given the following class (IncrementImpl) already written. Now we have so many threads which access this concurrently. How can I make it synchronize it.
Please help me.

Thanks,
Senthil.
-------------------
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are you expecting something more complicated than making the getCounter() method synchronized?
 
Senthil Kumaresan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ernest Friedman,
Thanks for your response. I think synchronizing getCounter method is enough.
Thanks a lot.
Senthil.
 
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suppose it's a little too academic, but declaring counter as volatile is an alternative solution, as long as you getCounter() method stays as atomic as it is.
 
reply
    Bookmark Topic Watch Topic
  • New Topic