I have a method in a class with mutable state that gets called 99.999 % from a single thread except that one time from a different thread in a shutdown hook.
Here is a skeleton of the class
public class StateHolder {
private final Queue<String> q;
public synchronized void add(String s) {
this.q.offer(s);
this.lastUpdateTime = System.currentTimeMillis();
}
public synchronized void removeUntil(Predicate<String> p) {
while(!q.isEmpty()) {
if (p.applies(q.peek()) {
q.poll();
} else {
break;
}
}
this.lastUpdateTime = System.currentTimeMillis();
}
public synchronized int pendingRecords() {
return this.q.size();
}
public synchronized void shutdown(Consumer<String> c) {
while(!q.isEmpty()) c.accept(q.poll());
}
}
In the above, methods add
, pendingRecords
and removeUntil
will be always called from the same thread during the lifetime of the application (1000+ calls per second depending of the traffic to the application). The shutdown
will be called by a different thread during the shutdown of the application which will happen once in weeks.
Is there a synchronization primitive that is known to be a better choice for performance for this access pattern? Or should I just use traditional synchronized
block and let the JIT figure it out?