Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronization problem: Please help me  RSS feed

 
Senthil Kumaresan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • 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;
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Ernest Friedman,
Thanks for your response. I think synchronizing getCounter method is enough.
Thanks a lot.
Senthil.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!