Skip to content

Commit f1109e4

Browse files
committedDec 11, 2024
examples: Simplify graceful shutdown in Hostname example
I've slept since I wrote the original code, so now I see a less repetitive implementation.
1 parent 6055adc commit f1109e4

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed
 

‎examples/example-hostname/src/main/java/io/grpc/examples/hostname/HostnameServer.java

+9-9
Original file line numberDiff line numberDiff line change
@@ -64,17 +64,17 @@ public void run() {
6464
// Start graceful shutdown
6565
server.shutdown();
6666
try {
67-
// Wait for RPCs to complete processing
68-
if (!server.awaitTermination(30, TimeUnit.SECONDS)) {
69-
// That was plenty of time. Let's cancel the remaining RPCs
70-
server.shutdownNow();
71-
// shutdownNow isn't instantaneous, so give a bit of time to clean resources up
72-
// gracefully. Normally this will be well under a second.
73-
server.awaitTermination(5, TimeUnit.SECONDS);
74-
}
67+
// Wait up to 30 seconds for RPCs to complete processing.
68+
server.awaitTermination(30, TimeUnit.SECONDS);
7569
} catch (InterruptedException ex) {
76-
server.shutdownNow();
70+
Thread.currentThread().interrupt();
7771
}
72+
// Cancel any remaining RPCs. If awaitTermination() returned true above, then there are no
73+
// RPCs and the server is already terminated. But it is safe to call even when terminated.
74+
server.shutdownNow();
75+
// shutdownNow isn't instantaneous, so you want an additional awaitTermination() to give
76+
// time to clean resources up gracefully. Normally it will return in well under a second. In
77+
// this example, the server.awaitTermination() in main() provides that delay.
7878
}
7979
});
8080
// This would normally be tied to the service's dependencies. For example, if HostnameGreeter

0 commit comments

Comments
 (0)