Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe circular buffer in Java

Consider a few web server instances running in parallel. Each server holds a reference to a single shared "Status keeper", whose role is keeping the last N requests from all servers.

For example (N=3):

Server a: "Request id = ABCD"        Status keeper=["ABCD"] Server b: "Request id = XYZZ"        Status keeper=["ABCD", "XYZZ"]  Server c: "Request id = 1234"        Status keeper=["ABCD", "XYZZ", "1234"] Server b: "Request id = FOO"         Status keeper=["XYZZ", "1234", "FOO"] Server a: "Request id = BAR"         Status keeper=["1234", "FOO", "BAR"] 

At any point in time, the "Status keeper" might be called from a monitoring application that reads these last N requests for an SLA report.

What's the best way to implement this producer-consumer scenario in Java, giving the web servers higher priority than the SLA report?

CircularFifoBuffer seems to be the appropriate data structure to hold the requests, but I'm not sure what's the optimal way to implement efficient concurrency.

like image 425
Adam Matan Avatar asked Jun 18 '12 08:06

Adam Matan


People also ask

Is circular buffer thread-safe?

Thread-Safety This means the circular_buffer is not thread-safe. The thread-safety is guarantied only in the sense that simultaneous accesses to distinct instances of the circular_buffer are safe, and simultaneous read accesses to a shared circular_buffer are safe.

What is circular buffer Java?

Ring Buffer (or Circular Buffer) is a bounded circular data structure that is used for buffering data between two or more threads. As we keep writing to a ring buffer, it wraps around as it reaches the end.

Is circular buffer the same as ring buffer?

A circular buffer is a popular way to implement a data stream because the code can be compact. A ring buffer is also known as a circular buffer, circular queue or cyclic buffer.

What is the difference between circular queue and circular buffer?

A Circular Queue is an extension of the Queue data structure such that the last element of the queue links to the first element. It is known as Ring Buffer, Circular Buffer or Cyclic Buffer.


1 Answers

Buffer fifo = BufferUtils.synchronizedBuffer(new CircularFifoBuffer()); 
like image 77
MahdeTo Avatar answered Sep 21 '22 03:09

MahdeTo