Reputation: 1675
For this code in a multiple thread environment, is the synchronized(c) necessary?
SynchronizedCounter c = new SynchronizedCounter();
synchronized(c){
c.increment();
c.value();
}
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
Upvotes: 0
Views: 85
Reputation: 26185
If you want the getValue call to see the result of the increment, without intervening increment or decrement from another thread, you do need the synchronized(c).
This is a sufficiently common requirement that similar designs often return the new value from an increment or decrement call. See, for example, java.util.concurrent.atomic.AtomicInteger. It has methods such as incrementAndGet().
Incidentally, if you are really using this code, rather than just using it to illustrate your question, consider using AtomicInteger instead.
Upvotes: 1
Reputation: 18440
It is needed if you want to make sure that when you call c.value()
after c.increment();
you are getting the value + 1
To avoid the situation that another thread2
calls c.decrement()
between the call of c.increment()
and c.value()
in thread1
Upvotes: 1