From a8dc3f73d47996d91b7163d681c089ae6225c7fa Mon Sep 17 00:00:00 2001 From: old driver Date: Mon, 26 Jul 2021 14:32:53 +0800 Subject: [PATCH] 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 () 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. --- .../netty/util/concurrent/DefaultPromise.java | 39 +++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java index 8c218cd5df..f23b920bcf 100644 --- a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java +++ b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java @@ -542,15 +542,14 @@ public class DefaultPromise implements Promise { checkDeadLock(); - long startTime = System.nanoTime(); - long waitTime = timeoutNanos; - boolean interrupted = false; - try { - for (;;) { - synchronized (this) { - if (isDone()) { - return true; - } + // Start counting time from here instead of the first line of this method, + // to avoid/postpone performance cost of System.nanoTime(). + final long startTime = System.nanoTime(); + synchronized (this) { + boolean interrupted = false; + try { + long waitTime = timeoutNanos; + while (!isDone() && waitTime > 0) { incWaiters(); try { wait(waitTime / 1000000, (int) (waitTime % 1000000)); @@ -563,19 +562,19 @@ public class DefaultPromise implements Promise { } finally { decWaiters(); } - } - if (isDone()) { - return true; - } else { - waitTime = timeoutNanos - (System.nanoTime() - startTime); - if (waitTime <= 0) { - return isDone(); + // Check isDone() in advance, try to avoid calculating the elapsed time later. + if (isDone()) { + return true; } + // 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(); } } }