简体   繁体   中英

Java Concurrency: Shared Memory Between Threads

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.

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.

Well, no. It will lock the whole object, but that's probably what you meant anyway...

data has 1000+ variables ...

Option 1

If you have enough memory, you could simply have an Object[] locks = new Object[1000]; for which you acquire the locks on.

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

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 the java.util.concurrent.atomic package .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM