I have a object obj that is read by many threads frequently , but updated by only one thread periodically.The update happens after long some interval (say 10 minutes).
The data is less transnational.Meaning if read threads gets stale data(old) for some time then its perfectly ok.
Now i thought of using following approach for synchronization:
final Object lock = new Object();
private MyObject obj = new MyObject(); //this is the data
public String getDataFieldName(){
synchronized(lock){
return this.obj.name;
}
}
/*the following code is wrong right?As its just synchronizes the code for getting reference.But after getting reference read thread R1 may try to get data while write Thread is modifying data.Will that give exception?How to solve this? */
public String getData(){
synchronized(lock){
return this.obj;
}
}
//only one thread can update.But how multipe threads can read at once?
public updateData(args ) {
synchronized(lock){
//do update
}
}
My questions are as follows:
-
I dont want only one thread to read the data.Reads should be parallel.
-
How can i synchronize read and write ?If write thread is updating and read thread is reading i dont what to get some exception.It is ok if read gets some old data
3)If read thread is reading while write thread is updating , will i get exception?Will there be any problem?
You don’t need any synchronization in this scenario. All you have to do is the following:
MyObjectis immutable, meaning that you never change any values in your object Instead you construct a newMyDataobject everytime you change it. This prevents anyone from seeing a half-changed object.You will never get an exception because of concurrent reads and writes if you follow these steps.