跳到主要内容

并发控制

deadLock and Lost Update​

todo deadLock and Lost Update

synchronized 关键字​

todo monitor lock​

每个对象都有一个锁,当线程运行到synchronized(上锁的对象) 代码段,线程把对象锁上了,就像用了一把虚拟的钥匙一样。当synchronized(上锁的对象) 代码段执行完毕,线程才会打开对象的锁,就像把虚拟钥匙还回去了一样。

synchronized 关键字必须有一个上锁的对象,即 Object 的子类 类对象或 Object 的子类 实例对象。

互斥性​

synchronized 关键字保证了同时只能有一个线程持有锁,其他线程和这个持有锁的线程互斥,就处于等待中。

同一把锁,锁的是相同的对象,不一定锁相同的代码块。

隐式锁和显式锁​

隐式锁:起作用的是内置锁。synchronized 放在普通方法上锁的是当前对象实例(相当于 synchronized(this))。synchronized 放在静态方法上,锁得当前类的class对象(调用getClass(),返回的那个类。getClass Returns the runtime class of this Object)。

显式锁:synchronized 修饰代码块,可以锁任意的对象,比如:this, num转换成的Integer对象synchronized(intVar);。也可以显式锁其他类的对象。synchronized(objectA);

其他​

synchronized 锁对象实例的时候。每个实例实际上是单独不同的一把锁。实例之间没有互斥的效果。

Even if an object has more than one synchronized method, there is still only one key. Once any thread has entered a synchronized method on that object, no thread can enter any other synchronized method on the same object. This restriction lets you protect your data by synchronizing any method that manipulates the data.

Nope, it’s not a good idea. Synchronization doesn’t come for free. First, a synchronized method has a certain amount of overhead. In other words, when code hits a synchronized method, there’s going to be a performance hit (although typically, you’d never notice it) while the matter of “is the key available?” is resolved. Second, a synchronized method can slow your program down because synchronization restricts concurrency. In other words, a synchronized method forces other threads to get in line and wait their turn. This might not be a problem in your code, but you have to consider it. Third, and most frightening, synchronized methods can lead to deadlock! (We’ll see this in a couple of pages.)

todo Atomic variables​

Atomic variables, with CAS operations, may be suitable if it’s just one value that is being changed by multiple threads.

todo optimistic locking.​

immutable data​

public final class ImmutableData { //We don’t want to allow subclasses that might add mutable values, so make this immutable class final.
private final String name; //All fields should be FINAL. The value will be set once, in the field declaration or constructor, and cannot be changed afterward.
private final int value;
public ImmutableData(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() { return name; }
public int getValue() { return value; }
}

Java 16 introduced records, which are immutable data classes provided directly by the language.

CopyOnWriteArrayList​