Java Concurrency: shared memory between threads

Suppose I have a Singleton class (any class can get an 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 a Singleton instance of this class. I am trying to figure out a way to synchronize get / sets based on PER FIELD.

If I have a synchronized getter / setter method for each variable, then this will "block" the entire class (instead of a separate field) until this method is installed.

Is there a way for these threads to only block instance values ​​instead of locking the entire class?

- EDIT: I apologize for the huge data of one object.

data is actually stored in several classes. In most cases, each object has only 20-25 members.

+3
1

getter/setter , "" ( ) , .

, . , , , , ...

1000+ ...

1

, Object[] locks = new Object[1000];, .

public void setColor(Color newCol) {
    synchronized (locks[17]) {
        sun = newCol;
    }
}

2

volatile. , , , .

3

AtomicLong, AtomicReference, AtomicBoolean,... .. java.util.concurrent.atomic.

+5

Source: https://habr.com/ru/post/1775753/


All Articles