Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Design pattern for method that gets called excessively

What's the best practice in Java to protect a method from being called excessively, while still keeping it non-blocking?

My usecase is a custom buffer for audio data. The buffer's method through which data can be polled from it must be non-blocking, and it is acceptable for the method to return null when no data is available. It's not acceptable for the method to be blocking, so I do not want to make it synchronized. When the method is called excessively the sound quality decreases. So how can I protect the method under heavy load, without relying on callers to behave themselves?

My current approach is to remember the timestamp of the last poll and return null if it's shorter ago than 3ms, but this feels a bit "hacky"...

like image 580
edr Avatar asked Aug 14 '26 06:08

edr


1 Answers

ConcurrentLinkedQueue does just that. It is non-blocking and returns null if no messages are available. Either that or a ConcurrentLinkedDequeue

like image 159
John Vint Avatar answered Aug 16 '26 21:08

John Vint