Avoid synchronizing on this and use an internal monitor instead

Where possible, code that previously synchronized on this (or on the
class in the case of static methods) has been updated to use an
internal monitor object instead. This allows the locking model that's
employed to be an implementation detail rather than part of the
class's API.

Classes that override a synchronized method continue to declare
the overriding method as synchronized. This ensures that locking
is consistent across the superclass and its subclass.

Closes gh-6262
This commit is contained in:
Andy Wilkinson
2016-07-01 10:00:29 +01:00
parent f9c7db1137
commit 92bb24e365
25 changed files with 685 additions and 511 deletions

View File

@@ -89,6 +89,8 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor {
private static class Verification {
private final Object monitor = new Object();
private final MockingProgress progress;
Verification(Object target) {
@@ -101,25 +103,29 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor {
this.progress = (MockingProgress) ReflectionUtils.getField(field, container);
}
public synchronized boolean isVerifying() {
VerificationMode mode = this.progress.pullVerificationMode();
if (mode != null) {
this.progress.verificationStarted(mode);
return true;
public boolean isVerifying() {
synchronized (this.monitor) {
VerificationMode mode = this.progress.pullVerificationMode();
if (mode != null) {
this.progress.verificationStarted(mode);
return true;
}
return false;
}
return false;
}
public synchronized void replaceVerifyMock(Object source, Object target) {
VerificationMode mode = this.progress.pullVerificationMode();
if (mode != null) {
if (mode instanceof MockAwareVerificationMode) {
MockAwareVerificationMode mockAwareMode = (MockAwareVerificationMode) mode;
if (mockAwareMode.getMock() == source) {
mode = new MockAwareVerificationMode(target, mockAwareMode);
public void replaceVerifyMock(Object source, Object target) {
synchronized (this.monitor) {
VerificationMode mode = this.progress.pullVerificationMode();
if (mode != null) {
if (mode instanceof MockAwareVerificationMode) {
MockAwareVerificationMode mockAwareMode = (MockAwareVerificationMode) mode;
if (mockAwareMode.getMock() == source) {
mode = new MockAwareVerificationMode(target, mockAwareMode);
}
}
this.progress.verificationStarted(mode);
}
this.progress.verificationStarted(mode);
}
}