Lock

Lock

Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

锁实现提供了比使用同步方法和语句更广泛的锁操作。它们允许更灵活的结构,具有完全不同的属性,并且可能支持多个关联的条件对象。

A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.

锁是一种工具,用于控制多个线程对共享资源的访问。通常,锁提供对共享资源的独占访问:一次只有一个线程可以获得锁,而对共享资源的所有访问都要求首先获得锁。但是,有些锁可能允许并发访问共享资源,比如读写锁的读锁。

The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

使用synchronized方法或语句块提供与每个对象关联的隐式监视器锁,但所有锁获取和释放都发生在块结构方式:在获得多个锁时,它们必须以相反的顺序来释放,和所有的锁都必须在相同的词法作用域。

While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of “hand-over-hand” or “chain locking”: you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

虽然synchronized方法和语句块的作用域机制使使用监视器锁进行编程变得更容易,并有助于避免许多涉及锁的常见编程错误,但是在某些情况下,您需要以更灵活的方式使用锁。例如,一些遍历并发访问的数据结构的算法需要使用“hand-over-hand”或“chain locked”:先获取节点A的锁,然后是节点B,然后释放A并获取C,然后释放B并获取D,等等。Lock接口的实现允许在不同的范围内获取和释放锁,并允许以任意顺序获取和释放多个锁,从而支持使用这些技术。

With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used:

这种灵活性的增加带来了额外的责任。块结构锁的缺失消除了同步方法和语句块发生时锁的自动释放。在大多数情况下,应该使用以下习语:

1
2
3
4
5
6
7
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}

When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.

当锁定和解锁发生在不同的作用域时,必须注意确保持有锁时执行的所有代码都受到try-finally或try-catch的保护,以确保在必要时释放锁。

Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly, and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).

Lock的实现比使用同步方法和语句块提供额外的功能在通过提供一个非阻塞的尝试获得一个锁(tryLock()),企图获得锁,可以打断(lockInterruptibly,企图获得锁可以超时(tryLock(long,TimeUnit))。

A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics.

Lock类还可以提供与隐式监视器锁完全不同的行为和语义,如保证顺序、不可重入使用或死锁检测。如果实现提供了这种专门的语义,那么实现必须记录这些语义。

Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.

请注意,Lock实例只是普通对象,它们本身可以用作synchronized语句中的目标。获取Lock实例的监视器锁与调用该实例的任何Lock方法没有指定的关系。为了避免混淆,建议您永远不要以这种方式使用锁实例,除非在它们自己的实现中。

Except where noted, passing a null value for any parameter will result in a NullPointerException being thrown.

除非特别指出,为任何参数传递null值都会导致抛出NullPointerException。

Memory Synchronization

内存同步

All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification (17.4 Memory Model) :

所有的Lock实现都必须执行与内置监视器锁提供的相同的内存同步语义,如Java语言规范(17.4内存模型)中所述:

A successful lock operation has the same memory synchronization effects as a successful Lock action.

成功的Lock操作与成功的锁动作具有相同的内存同步效果。

A successful unlock operation has the same memory synchronization effects as a successful Unlock action.

成功的解锁操作与成功的解锁动作具有相同的内存同步效果。

Unsuccessful locking and unlocking operations, and reentrant locking/unlocking operations, do not require any memory synchronization effects.

不成功的锁定和解锁操作以及重入锁定/和解锁操作不需要任何内存同步效果。

Implementation Considerations

实现注意事项

The three forms of lock acquisition (interruptible, non-interruptible, and timed) may differ in their performance characteristics, ordering guarantees, or other implementation qualities. Further, the ability to interrupt the ongoing acquisition of a lock may not be available in a given Lock class. Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of lock acquisition, nor is it required to support interruption of an ongoing lock acquisition. An implementation is required to clearly document the semantics and guarantees provided by each of the locking methods. It must also obey the interruption semantics as defined in this interface, to the extent that interruption of lock acquisition is supported: which is either totally, or only on method entry.

三种形式的锁获取(可中断续、不可中断续和定时)在性能特征、顺序保证或其他实现质量方面可能有所不同。此外,中断正在进行的锁获取的能力可能在给定的锁类中不可用。因此,实现不需要为所有三种形式的锁获取定义完全相同的保证或语义,也不需要支持正在进行的锁获取的中断。需要一个实现来清楚地记录每个锁定方法提供的语义和保证。它还必须遵守这个接口中定义的中断语义,前提是支持锁获取的中断:要么完全支持,要么只支持方法入口。

As interruption generally implies cancellation, and checks for interruption are often infrequent, an implementation can favor responding to an interrupt over normal method return. This is true even if it can be shown that the interrupt occurred after another action may have unblocked the thread. An implementation should document this behavior.

由于中断通常意味着取消,而且对中断的检查通常不频繁,所以实现可能更倾向于响应中断,而不是正常的方法返回。即使可以显示在另一个操作之后发生的中断可能已经解除了线程阻塞,这也是正确的。实现应该记录这种行为。

lock()

Acquires the lock.

获得锁。

If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.

如果锁不可用,则当前线程将出于线程调度目的而禁用,并处于休眠状态,直到获得锁为止。

Implementation Considerations

实现注意事项

A Lock implementation may be able to detect erroneous use of the lock, such as an invocation that would cause deadlock, and may throw an (unchecked) exception in such circumstances. The circumstances and the exception type must be documented by that Lock implementation.

锁实现可能能够检测锁的错误使用,例如导致死锁的调用,并可能在这种情况下抛出(未选中的)异常。该锁实现必须记录环境和异常类型。

lockInterruptibly()

Acquires the lock unless the current thread is interrupted.

除非当前线程中断,否则获取锁。

Acquires the lock if it is available and returns immediately.

如果锁可用,则获取锁并立即返回。

If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:

如果锁不可用,那么当前线程将出于线程调度的目的被禁用,并处于休眠状态,直到发生以下两种情况之一:

  • The lock is acquired by the current thread; or
  • Some other thread interrupts the current thread, and interruption of lock acquisition is supported.

锁被当前线程获取;或

其他一些线程中断当前线程,支持中断锁获取。

If the current thread:

  • has its interrupted status set on entry to this method; or
  • is interrupted while acquiring the lock, and interruption of lock acquisition is supported,

then InterruptedException is thrown and the current thread’s interrupted status is cleared.

如果当前线程:

  • 在进入此方法时已设置其中断状态;或

  • 获取锁时中断,支持锁获取中断,

然后抛出InterruptedException,并清除当前线程的中断状态。

tryLock()

Acquires the lock only if it is free at the time of invocation.
Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false.
A typical usage idiom for this method would be:

仅当锁在调用时处于空闲状态时才获取锁。

如果锁可用,则获取锁并立即返回值true。如果锁不可用,则此方法将立即返回值false。

这种方法的典型用法是:

1
2
3
4
5
6
7
8
9
10
11
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}

This usage ensures that the lock is unlocked if it was acquired, and doesn’t try to unlock if the lock was not acquired.

Returns:
true if the lock was acquired and false otherwise

这种用法确保锁在被获取时被解锁,而在未被获取时不会尝试解锁。

返回:

如果锁被获取,则为真,否则为假

tryLock(long time,@NotNull TimeUnit unit)

Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.

如果在给定的等待时间内是空闲的并且当前线程没有被中断,则获取锁。

If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:

如果锁可用,则此方法立即返回值true。如果锁不可用,那么当前线程将出于线程调度的目的而被禁用,并处于休眠状态,直到发生以下三种情况之一:

  • The lock is acquired by the current thread; or
  • Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or
  • The specified waiting time elapses

  • 锁被当前线程获取;或

  • 其他线程中断当前线程,支持锁获取中断;或
  • 指定的等待时间已经过了

If the lock is acquired then the value true is returned.

如果获得锁,则返回true值。

If the current thread:

如果当前线程:

  • has its interrupted status set on entry to this method; or
  • is interrupted while acquiring the lock, and interruption of lock acquisition is supported,

  • 在进入此方法时已设置其中断状态;或

  • 获取锁时中断,支持锁获取中断,

then InterruptedException is thrown and the current thread’s interrupted status is cleared.

然后抛出InterruptedException,并清除当前线程的中断状态。

If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.

如果指定的等待时间过期,则返回false值。如果时间小于或等于0,则该方法根本不会等待。

unlock()

Releases the lock.

释放锁。

<<<<<<< HEAD

newCondition()

Returns a new Condition instance that is bound to this Lock instance.

返回绑定到此Lock实例的新Condition实例。

Before waiting on the condition the lock must be held by the current thread.

在等待condition之前,lock必须由当前线程持有。

=======

ReentrantLock

cd5e525a1e5dff253b35ecddf2d8e771229733ad

关于Lock与synchronized关键字在锁的处理上的重要差别

  1. 锁的获取方式:前者是通过程序代码的方式由开发者手工获取,后者是通过JVM来获取(无需开发者干预)
  2. 具体实现方式:前者是通过Java代码的方式来实现,后者是通过JVM底层来实现(无需开发者关注)
  3. 锁的释放方式:前者务必通过unlock()方法在finally块中手工释放,后者通过JVM来释放(无需开发者关注)
  4. 锁的具体类型:前者提供了多种,入公平锁、非公平锁,后者与前者均提供了可重入锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 关于Lock与synchronized关键字在锁的处理上的重要差别
* 1. 锁的获取方式:前者是通过程序代码的方式由开发者手工获取,后者是通过JVM来获取(无需开发者干预)
* 2. 具体实现方式:前者是通过Java代码的方式来实现,后者是通过JVM底层来实现(无需开发者关注)
* 3. 锁的释放方式:前者务必通过unlock()方法在finally块中手工释放,后者通过JVM来释放(无需开发者关注)
* 4. 锁的具体类型:前者提供了多种,入公平锁、非公平锁,后者与前者均提供了可重入锁
*/
public class MyTest1 {
private Lock lock = new ReentrantLock();
public void method1() {
try {
this.lock.lock();
System.out.println("method1 invoked");
} finally {
this.lock.unlock();
}
}
public void method2() {
try {
this.lock.lock();
System.out.println("method2 invoked");
} finally {
this.lock.unlock();
}
// boolean result = false;
//
// try {
// result = lock.tryLock(800, TimeUnit.MILLISECONDS);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// if (result) {
// System.out.println("get the lock");
// } else {
// System.out.println("can't get the lock");
// }
}
public static void main(String[] args) {
MyTest1 myTest1 = new MyTest1();
Thread thread1 = new Thread(()->{
for (int i = 0; i < 10; i++) {
myTest1.method1();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(()->{
for (int i = 0; i < 10; i++) {
myTest1.method2();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}