I have a data class with lots of data in it (TV schedule data). The data is queried from one side and periodically updated from the other side. There are two threads: the first thread queries the data on request and the second thread updates the data on regular intervals. To prevent locking, I use two instances (copies) of the data class: the live instance and the backup instance. Initially, both instances are filled with the same data. The first thread only reads from the live instance. The second thread periodically updates both instances as follows:
- Update the backup instance.
- Swap the backup and live instance (i.e. the backup instance becomes the live instance).
- Update the backup instance.
- Both backup instance and live instance are now up-to-date.
My questions is: how should I use the volatile keyword here?
public class data
{
// Lots of fields here.
// Should these fields also be declared volatile?
}
I have already made the references volatile:
public volatile data live
public volatile data backup