Question: 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?

Answer: 
I believe you will take advantage (out of the box) of bias locking - [Biased locking in java](https://stackoverflow.com/questions/9439602/biased-locking-in-java)
First of all, you need to clarify the semantics of calls to `add`, `pendingRecords` and `removeUntil` when a concurrent call to `shutdown` happens. In the current implementation those calls will be blocked until `shutdown` returns but afterwards they will happily continue. Maybe it would be better to throw an `IllegalStateException` in this case. But this really depends on your requirements.

To improve the concurrency aspect I would separate the life cycle concern of `shutdown` from the rest of the application logic. For example you could change `q` from `Queue<String>` to `AtomicReference<Queue<String>>`. A call to `shutdown` would then set that reference to a `Queue` implementation that would represent the shutdown being in progress and e.g. throw `IllegalStateException`s on all their methods. Depending on the exact semantics you require there are still other concurrency related issues to sort out then. E.g. Is it fine for `removeUntil` to start failing in the middle of the loop? If not that method would need to operate from a local copy of the queue acquired when the method was entered.