I am having a Server storing data from clients.
Every Client works in his own Thread and is having one Data-Object.
This Data-Object is a custom class, lets call is Data.java containing unspezific data, this could be some bytes but normally from around 100kb < Data < 2mb.
Now i have a backup-thread, iterating through the list of clients, parsing their data-object to xml using Xstream and storing this in a database.
But is this safe?
If the client is doing operations altering the Data while it is backed up (Assuming that clients send requests around every 0,1 seconds and that some request could endure around seconds altering the Data at all time in the process) this data could be corrupt.
What would be a good way to do it?
I am having a Server storing data from clients. Every Client works in his
Share
You can lock the object with
synchronizedor aLockwhenever you change or read the objects. I would also use aboolean dirty;flag which is set totruewhenever you alter it. That way your background thread only needs to save the objects which have changed.Since the client might be altering the data for a long period of time, I would consider using
lock.tryLock()which allows you to try and get the lock without blocking so the thread can still “backup” objects which are not locked. You can always re-try on the next cycle.An example