. WriterReaderPhaser (WRP) was designed for the common pattern of speed or latency critical writers writing and accumulating data into a data structure (e.g. a stats collecting thing, like a histogram), and less-critical background threads occasionally or periodically gathering up that accumulated data in a lossless manner. It provides for wait-free writers and potentially blocking readers. It's a common pattern used and needed when e.g. logging of metrics or other stats is performed periodically, and I've used the pattern often enough that I decided it needs a new synchronization primitive.
For a full code example of how to use this synchronization primitive in e.g. a classic double-buffered approach around a simple data structure, you can see how
an implementation of WriterReaderPhaser is used in HdrHistogram's
SingleWriterRecorder and
Recorder classes, both of which record data into an interval histogram, and provide for lossless reading of that interval histogram. Those are classic examples of stats written by latency critical writers in a wait-free manner, and collected by a non-latency critical background thread, and WriterReaderPhaser can be similarly used to coordinate this sort of work around any sort of stats-gathering data structure. The WRP's current implementation has the writer use an atomic increment (which translates to a LOCK XADD on x86) to
enter and
leave the critical section. Single writer cases need no further synchronization, and multi-writer cases would need to coordinate on writing to the common data structure (e.g. a
AtomicHistogram or
ConcurrentHistogram in Recorder, depending on whether or not auto-resizing of the histogram is needed).
A java implementation of WRP currently lives in HdrHistogram (which is available on maven central). It is too small for its own package and probably needs a better home. If interest in it grows, Martin can probably find it a home in Agrona. Other implementations have been built in e.g. other language versions of HdrHistogram (e.g.
C,
.NET).