Suppose I have a Singleton class (any class can get the instance):
class data
{
Color sun = "WHITE";
String luminance = "HIGH";
int age = 25;
double speed = 52.5
...
}
Suppose I have several threads that get a reference to the Singleton instance of this class. I’m trying to figure out a way to synchronize gets/sets on a PER FIELD basis.
If I have a synchronized getter/setter method for each variable, then this will basically “lock” the whole class(instead of the individual field) until that method is set.
Is there a way so that these threads only lock instance values instead of locking the whole class?
— EDIT: I apologize for the huge one object data.
data is actually stored in several classes. At most each object has only 20-25 members.
Well, no. It will lock the whole object, but that’s probably what you meant anyway…
Option 1
If you have enough memory, you could simply have an
Object[] locks = new Object[1000];for which you acquire the locks on.Option 2
Another option may be to mark all fields as
volatile. This will at least make sure that the reads and writes are atomically performed.Option 3
Have a look at
AtomicLong,AtomicReference,AtomicBoolean, … and so on in thejava.util.concurrent.atomicpackage.