What Cases Require Synchronized Method Access in Java?

In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class.

My question is when would I be incorrect if I do not synchronize instance members?

for example if my class is

public class MyClass {
    private int instanceVar = 0;

    public setInstanceVar()
    {
        instanceVar++;
    }

    public getInstanceVar()
    {
        return instanceVar;
    }
}

in what cases (of usage of the class MyClass ) would I need to have methods: public synchronized setInstanceVar() and public synchronized getInstanceVar() ?

Thanks in advance for your answers.


It depends on whether you want your class to be thread-safe. Most classes shouldn't be thread-safe (for simplicity) in which case you don't need synchronization. If you need it to be thread-safe, you should synchronize access or make the variable volatile. (It avoids other threads getting "stale" data.)


The synchronized modifier is really a bad idea and should be avoided at all costs. I think it is commendable that Sun tried to make locking a little easier to acheive, but synchronized just causes more trouble than it is worth.

The issue is that a synchronized method is actually just syntax sugar for getting the lock on this and holding it for the duration of the method. Thus, public synchronized void setInstanceVar() would be equivalent to something like this:

public void setInstanceVar() {
    synchronized(this) {
        instanceVar++;
    }
}

This is bad for two reasons:

  • All synchronized methods within the same class use the exact same lock, which reduces throughput
  • Anyone can get access to the lock, including members of other classes.
  • There is nothing to prevent me from doing something like this in another class:

    MyClass c = new MyClass();
    synchronized(c) {
        ...
    }
    

    Within that synchronized block, I am holding the lock which is required by all synchronized methods within MyClass . This further reduces throughput and dramatically increases the chances of a deadlock.

    A better approach is to have a dedicated lock object and to use the synchronized(...) block directly:

    public class MyClass {
        private int instanceVar;
        private final Object lock = new Object();     // must be final!
    
        public void setInstanceVar() {
            synchronized(lock) {
                instanceVar++;
            }
        }
    }
    

    Alternatively, you can use the java.util.concurrent.Lock interface and the java.util.concurrent.locks.ReentrantLock implementation to achieve basically the same result (in fact, it is the same on Java 6).


    如果你想让这个类的线程安全,我会声明instanceVarvolatile ,以确保始终获得来自内存的最新值,并且还会使setInstanceVar() synchronized因为在JVM中,增量不是原子操作。

    private volatile int instanceVar =0;
    
    public synchronized setInstanceVar() { instanceVar++;
    
    }
    
    链接地址: http://www.djcxy.com/p/76268.html

    上一篇: 同步本地变量

    下一篇: 什么情况下需要在Java中同步方法访问?