Java How to synchronize getters and setters correctly?

If there are several mutable properties in an object that will be executed by multiple threads, I understand that they should be synchronized

class Doggie {
    private String name;
    private int    age;

    public void setName(String name) { this.name = name; }
    public String getName() { return this.name; }
    public void setAge(int age) { this.age = age; }
    public int getAge() { return this.age; }

}

Question:

>There are no atomic operations of return and assignment in Java? > Because attributes may not necessarily be related to each other, synchronization with the same lock does not always make sense How to organize locking structures? > Is internal locking or private object locking better?

Solution

Yes, they are atomic (at least in some cases), but atomicity is not the only problem Another important question is whether a thread's write operation to an attribute is guaranteed to be visible for subsequent reads of the same attribute made by different threads

>When reading and writing are in the same thread, reading will ensure that earlier writes are seen. > When the read and write are in different threads, the read can only guarantee to see the earlier write. If the two threads are synchronized correctly... Or the attribute is declared volatile

Note that the original lock / mutex is not the only way to synchronize

If (and only) lock contention is possible, it makes sense to use multiple locks In your example, lock contention can only be a problem if some doggie instances receive very high rates of get and / or set operations

It depends on If your application is using the original locking of doggie objects, you may encounter lock contention or even accidental locking of get and set operations In this case, a private lock may be desirable Otherwise, private locks are unnecessary overhead

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>