Мне нужно реализовать глобальную статистику сбора объектов для веб-сервера. У меня есть Statistics
singleton, у которого есть метод addSample(long sample)
, который впоследствии вызывает updateMax
. Это должно быть явно потокобезопасным. У меня есть этот метод для обновления максимум всей статистики:
AtomicLong max;
private void updateMax(long sample) {
while (true) {
long curMax = max.get();
if (curMax < sample) {
boolean result = max.compareAndSet(curMax, sample);
if (result) break;
} else {
break;
}
}
}
Правильно ли эта реализация? Я использую java.util.concurrent, потому что считаю, что это будет быстрее простого synchronized
. Есть ли другой/лучший способ реализовать это?