Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are regular Queues inappropriate to use when multithreading in Java?

I am trying to add asynchronous output to a my program.

Currently, I have an eventManager class that gets notified each frame of the position of any of the moveable objects currently present in the main loop (It's rendering a scene; some objects change from frame to frame, others are static and present in every frame). I am looking to record the state of each frame so I can add in the functionality to replay the scene.

This means that I need to store the changing information from frame to frame, and either hold it in memory or write it to disk for later retrieval and parsing.

I've done some timing experiments, and recording the state of each object to memory increased the time per frame by about 25% (not to mention the possibility of eventually hitting a memory limit). Directly writing each frame to disk takes (predictably) even longer, close to twice as long as not recording the frames at all.

Needless to say, I'd like to implement multithreading so that I won't lose frames per second in my main rendering loop because the process is constantly writing to disk.

I was wondering whether it was okay to use a regular queue for this task, or if I needed something more dedicated like the queues discussed in this question.

In my situation, there is only one producer (the main thread), and one consumer (the thread I want to asynchronously write to disk). The producer will never remove from the queue, and the consumer will never add to it - so do I need a specialized queue at all?

Is there an advantage to using a more specialized queue anyway?

like image 990
Raven Dreamer Avatar asked Jul 06 '26 04:07

Raven Dreamer


1 Answers

Yes, a regular Queue is inappropriate. Since you have two threads you need to worry about boundary conditions like an empty queue, full queue (assuming you need to bound it for memory considerations), or anomalies like visibility.

A LinkedBlockingQueue is best suited for your application. The put and take methods use different locks so you will not have lock contention. The take method will automatically block the consumer writing to disk if it somehow magically caught up with the producer rendering frames.

like image 156
Tim Bender Avatar answered Jul 08 '26 17:07

Tim Bender