com.github.phantomthief.failover.impl.PriorityFailoverCheckTask Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simple-failover Show documentation
Show all versions of simple-failover Show documentation
A simple failover library for Java
package com.github.phantomthief.failover.impl;
import java.util.HashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import com.github.phantomthief.failover.impl.PriorityFailover.GroupInfo;
import com.github.phantomthief.failover.impl.PriorityFailover.ResInfo;
import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.PriorityFailoverConfig;
/**
* @author huangli
* Created on 2020-01-20
*/
class PriorityFailoverCheckTask implements Runnable {
private final PriorityFailoverConfig config;
private volatile ScheduledFuture> future;
private final HashMap> resourcesMap;
private final GroupInfo[] groups;
private volatile boolean closed;
PriorityFailoverCheckTask(PriorityFailoverConfig config, PriorityFailover failover) {
this.config = config;
this.resourcesMap = failover.getResourcesMap();
this.groups = failover.getGroups();
if (config.getChecker() != null) {
if (config.isStartCheckTaskImmediately()) {
ensureStart();
}
GcUtil.register(failover, this::close);
GcUtil.doClean();
} else {
future = null;
}
}
public void ensureStart() {
if (future == null) {
synchronized (this) {
if (future == null) {
future = config.getCheckExecutor().scheduleWithFixedDelay(
this, config.getCheckDuration().toMillis(),
config.getCheckDuration().toMillis(), TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public void run() {
// TODO run in multi threads mode?
Thread currentThread = Thread.currentThread();
String origName = currentThread.getName();
if (config.getName() != null) {
currentThread.setName(origName + "-[" + config.getName() + "]");
}
try {
for (ResInfo r : resourcesMap.values()) {
if (closed) {
return;
}
if (config.getWeightFunction().needCheck(r.maxWeight,
r.minWeight, r.priority, r.currentWeight, r.resource)) {
boolean ok;
try {
ok = config.getChecker().test(r.resource);
} catch (Throwable e) {
ok = false;
}
if (closed) {
return;
}
PriorityFailover.updateWeight(ok, r, config, groups);
}
}
} finally {
currentThread.setName(origName);
}
}
public synchronized void close() {
closed = true;
if (future != null && !future.isCancelled()) {
future.cancel(true);
}
}
boolean isClosed() {
return closed;
}
}