Java – should I synchronize on ReferenceQueue?
I was looking at the source code of weakhashmap and came across:
private final ReferenceQueue<Object> queue = new ReferenceQueue<>(); private void expungeStaleEntries() { for (Object x; (x = queue.poll()) != null; ) { synchronized (queue) { /* snip */ } } }
Why is this method synchronized on ReferenceQueue? Weakhashmap itself does not require clue security:
This leads me to believe that this implementation detail is to ensure the thread safety of ReferenceQueue itself in some way (because GC will modify it from its own thread) However, the document for ReferenceQueue does not mention any concurrency issues. Instead, it looks at the source code of ReferenceQueue and shows that it cannot even synchronize itself (it uses internal locks)
Why does weakhashmap synchronize on ReferenceQueue? Should I synchronize every time ReferenceQueue is used?
Solution
If you look at ReferenceQueue, you will see that it explicitly supports threads within the platform because it indicates that the remove () method will be blocked until new entries are available
The synchronization seen in the weakhashmap is to ensure that multiple threads accessing the ReferenceQueue are synchronized correctly
You may find this related bug at bugs sun. Interesting. Com
To answer your question, I don't think external synchronization of ReferenceQueue is necessary if you ensure that it is accessed only by a single thread I won't use (and can't think of a good reason) a single ReferenceQueue as a consumer from multiple threads