Skip to content

Commit

Permalink
improve monitor creating, handle errors (#7867)
Browse files Browse the repository at this point in the history
  • Loading branch information
kylixs authored May 26, 2021
1 parent 2dace54 commit 49e6701
Showing 1 changed file with 13 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
Expand All @@ -55,7 +53,7 @@ public abstract class AbstractMonitorFactory implements MonitorFactory {
*/
private static final Map<String, Monitor> MONITORS = new ConcurrentHashMap<String, Monitor>();

private static final Map<String, CompletableFuture<Monitor>> FUTURES = new ConcurrentHashMap<String, CompletableFuture<Monitor>>();
private static final Map<String, Future<Monitor>> FUTURES = new ConcurrentHashMap<String, Future<Monitor>>();

/**
* The monitor create executor
Expand Down Expand Up @@ -85,10 +83,18 @@ public Monitor getMonitor(URL url) {
}

final URL monitorUrl = url;
final CompletableFuture<Monitor> completableFuture = CompletableFuture.supplyAsync(() -> AbstractMonitorFactory.this.createMonitor(monitorUrl));
FUTURES.put(key, completableFuture);
completableFuture.thenRunAsync(new MonitorListener(key), EXECUTOR);

future = EXECUTOR.submit(() -> {
try {
Monitor m = createMonitor(monitorUrl);
MONITORS.put(key, m);
FUTURES.remove(key);
return m;
} catch (Throwable e) {
logger.warn("Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: " + monitorUrl, e);
return null;
}
});
FUTURES.put(key, future);
return null;
} finally {
// unlock
Expand All @@ -98,28 +104,4 @@ public Monitor getMonitor(URL url) {

protected abstract Monitor createMonitor(URL url);


class MonitorListener implements Runnable {

private String key;

public MonitorListener(String key) {
this.key = key;
}

@Override
public void run() {
try {
CompletableFuture<Monitor> completableFuture = AbstractMonitorFactory.FUTURES.get(key);
AbstractMonitorFactory.MONITORS.put(key, completableFuture.get());
AbstractMonitorFactory.FUTURES.remove(key);
} catch (InterruptedException e) {
logger.warn("Thread was interrupted unexpectedly, monitor will never be got.");
AbstractMonitorFactory.FUTURES.remove(key);
} catch (ExecutionException e) {
logger.warn("Create monitor failed, monitor data will not be collected until you fix this problem. ", e);
}
}
}

}

0 comments on commit 49e6701

Please sign in to comment.