Do we have to synchronize a managed bean method if this method is called by e.g. commandButton
component as a AJAX request, and the method is operating on a instance variable of managed bean?
Let's say we have this simple managed bean :
public class ManagedBeanTest {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String increaseCount() {
count++;
return null;
}
}
So if in this case the increaseCount
method is called by a commandButton
component inside action
, do I have to synchronize this method?
Thank you for your answer.
When methods of managed bean should be synchronized?
When the managed bean is put in the wrong scope. In properly designed apps that is, thus, never.
In your particular example, you should be using AtomicInteger
instead of int
and possibly a bunch of synchronized
modifiers.
private AtomicInteger count = new AtomicInteger();
public int getCount() {
return count.get();
}
public void incrementCount() {
count.incrementAndGet();
}
// No setter!