Search code examples
javaconcurrencyjava.util.concurrent

Usage of lazySet on AtomicXXX in Java


From this question : AtomicInteger lazySet vs. set and form this link : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html

I could gather following points

  • lazySet could be faster than set
  • lazySet uses store-store barrier (writes before are honored but not the contended writes, which were yet to happen)

I could find one use-case where it could be applied, from the documentation :

  • Use lazySet when you want to null out a pointer to aid GC.

Are there any other practical use-cases for lazySet ?


Solution

  • Caffeine uses lazy or relaxed writes in many of its data structures.

    • When nulling out a field (e.g. ConcurrentLinkedStack)
    • When writing to volatile fields before publishing (e.g. SingleConsumerQueue)
    • When publish is safely delayable (e.g. BoundedBuffer)
    • When races are benign (e.g. cache expiration timestamps)
    • When inside a lock (e.g. BoundedLocalCache)

    ConcurrentLinkedQueue uses relaxed writes prior to publishing a node and may lazily sets a node's next field (prior to publishing or to indicate a stale traversal).

    You may also enjoy reading the Linux Kernel Memory Barriers paper.