Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • 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: 24215
37
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!