I need to write a bean that would act as a counter of how many times it was accessed.
I'm thinking of using @ApplicationScoped
bean with AtomicInteger
like that
@ApplicationScoped
class VisitsCounter {
private AtomicInteger counter;
@PostConstruct
public void construct() {
counter = new AtomicInteger(0);
}
public int visited() {
return counter.incrementAndGet();
}
}
My question is: is it ok when considering multiple requests at the same time? Or do i need to play with @ConcurrencyManagement
and @Lock
annotations? I suppose that Atomic*
should do the trick but I'm not sure.
Also does the same applies when I have thread safe collections as a fields? E.g. say I have
@ApplicationScoped
class ValuesHolder {
private List<String> values;
@PostConstruct
public void construct() {
values = Collections.synchronizedList(new LinkedList<String>());
}
public void insert(String value) {
values.add(value);
}
public String remove(String value) {
return values.remove(value);
}
}
are the operations really thread-safe?
It is said that concurrency annotations and locks should be used when there is modification of state of the bean, but what if my list already takes care of thread safety?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…