Optimize method io.netty.util.concurrent.DefaultPromise.await0(...) (#11504)

Motivation:

For the code pattern of `Object.wait(...)`  in `io.netty.util.concurrent.DefaultPromise.await0(...)`, it's better to follow the recommended code pattern according to [Object.wait(...)'s doc](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()):
```
synchronized (obj) {
     while (<condition does not hold>)
     obj.wait();
     ... // Perform action appropriate to condition
}
```

Modification:
Change the `Object.wait(...)`'s code pattern in `io.netty.util.concurrent.DefaultPromise.await0(...)`.

Result:

The `Object.wait(...)`'s code pattern in `io.netty.util.concurrent.DefaultPromise.await0(...)` meets the Java doc.
This commit is contained in:
old driver 2021-07-26 14:32:53 +08:00 committed by Norman Maurer
parent 6e5537f312
commit a8dc3f73d4

View File

@ -542,15 +542,14 @@ public class DefaultPromise<V> implements Promise<V> {
checkDeadLock(); checkDeadLock();
long startTime = System.nanoTime(); // Start counting time from here instead of the first line of this method,
long waitTime = timeoutNanos; // to avoid/postpone performance cost of System.nanoTime().
boolean interrupted = false; final long startTime = System.nanoTime();
try { synchronized (this) {
for (;;) { boolean interrupted = false;
synchronized (this) { try {
if (isDone()) { long waitTime = timeoutNanos;
return true; while (!isDone() && waitTime > 0) {
}
incWaiters(); incWaiters();
try { try {
wait(waitTime / 1000000, (int) (waitTime % 1000000)); wait(waitTime / 1000000, (int) (waitTime % 1000000));
@ -563,19 +562,19 @@ public class DefaultPromise<V> implements Promise<V> {
} finally { } finally {
decWaiters(); decWaiters();
} }
} // Check isDone() in advance, try to avoid calculating the elapsed time later.
if (isDone()) { if (isDone()) {
return true; return true;
} else {
waitTime = timeoutNanos - (System.nanoTime() - startTime);
if (waitTime <= 0) {
return isDone();
} }
// Calculate the elapsed time here instead of in the while condition,
// try to avoid performance cost of System.nanoTime() in the first loop of while.
waitTime = timeoutNanos - (System.nanoTime() - startTime);
}
return isDone();
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
} }
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
} }
} }
} }