szetszwo commented on code in PR #733:
URL: https://github.com/apache/ratis/pull/733#discussion_r963468832


##########
ratis-common/src/main/java/org/apache/ratis/util/Daemon.java:
##########
@@ -17,24 +17,76 @@
  */
 package org.apache.ratis.util;
 
+import javax.annotation.Nullable;
+import java.util.concurrent.atomic.AtomicReference;
+
 public class Daemon extends Thread {
   {
     setDaemon(true);
   }
 
-  /** Construct a daemon thread. */
+  /** If the thread meets an uncaught exception, this field will be set. */
+  private final AtomicReference<Throwable> throwable = new 
AtomicReference<>(null);
+  private ErrorRecorded statedServer;
+
+  /** Construct a daemon thread with no arguments, left only for extension. */
   public Daemon() {
     super();
+    setUncaughtExceptionHandler((thread, t) -> {
+      onError(t);
+    });
+  }
+
+  /** Construct a daemon thread with flexible arguments. */
+  public Daemon(Builder builder) {
+    super(builder.runnable);
+    setName(builder.name);
+    this.statedServer = builder.statedServer;
+    setUncaughtExceptionHandler((thread, t) -> {
+      onError(t);
+    });
+  }
+
+  /**
+   * This will be invoked on uncaught exceptions.
+   * Necessary bookkeeping or graceful exit logics should be put here.
+   *
+   * @param t the crashing error
+   */
+  public void onError(Throwable t) {
+    throwable.set(t);
+    if (statedServer != null) {
+      // Rely on the server to log
+      statedServer.setError(t);
+    }
   }
 
-  /** Construct a daemon thread with the given runnable. */
-  public Daemon(Runnable runnable) {
-    this(runnable, runnable.toString());
+  @Nullable
+  public Throwable getError() {
+    return throwable.get();
   }
 
-  /** Construct a daemon thread with the given runnable. */
-  public Daemon(Runnable runnable, String name) {
-    super(runnable);
-    this.setName(name);
+  public static class Builder {
+    private final String name;
+    private Runnable runnable;
+    private ErrorRecorded statedServer;
+
+    public Builder(String name) {

Review Comment:
   We may enforce it in the `build()` method as below:
   ```java
   Objects.requireNonNull(name, "name == null");
   ``` 
   A Builder should not have parameters in its constructor.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to