Non-blocking MySQL updates with java?
For a multiplayer game I'm working on, I would like to write events to the mysql database without blocking the game's update thread, so that if the database is busy or the table is locked, the game doesn't stop working while it is waiting for a write.
What's the best way to accomplish this?
I am using c3p0 to manage a pool of database connections. My best idea is to add query update lines to a synchronized list, with an independent thread checking the list every 100ms and executing the requests it finds there.
a source to share
My best idea is to add query update lines to a synchronized list, with an independent thread checking the list every 100ms and executing the requests it finds there.
This sounds good to me if you don't want to block your main thread, except not using a synchronized list and 100ms polling, but use BlockingQueue . LinkedBlockingQueue should do the job, if you make it unlimited, it will never block your main thread.
a source to share
Put updates in BlockingQueue
. Ask a separate thread to wait in the queue using take()
and then drainTo()
to consume all pending updates and push them to the server in one go. Use a single multi-line INSERT for maximum efficiency.
This approach ensures that updates reach the server without any irretrievable delay due to the polling rate, making the requests louder and therefore more efficient when the volume goes up.
a source to share