fix ExecutorRouteRound count++ concurrency problems, use AtomicInteger replace Integer

This commit is contained in:
jinghui.lin 2020-08-05 18:46:39 +08:00
parent b99382d114
commit 15d8bcd517
1 changed files with 12 additions and 5 deletions

View File

@ -8,14 +8,16 @@ import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Created by xuxueli on 17/3/10. * Created by xuxueli on 17/3/10.
*/ */
public class ExecutorRouteRound extends ExecutorRouter { public class ExecutorRouteRound extends ExecutorRouter {
private static ConcurrentMap<Integer, Integer> routeCountEachJob = new ConcurrentHashMap<Integer, Integer>(); private static ConcurrentMap<Integer, AtomicInteger> routeCountEachJob = new ConcurrentHashMap<>();
private static long CACHE_VALID_TIME = 0; private static long CACHE_VALID_TIME = 0;
private static int count(int jobId) { private static int count(int jobId) {
// cache clear // cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) { if (System.currentTimeMillis() > CACHE_VALID_TIME) {
@ -23,11 +25,16 @@ public class ExecutorRouteRound extends ExecutorRouter {
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24; CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
} }
AtomicInteger count = routeCountEachJob.get(jobId);
// 初始化时主动Random一次缓解首次压力
if (count == null || count.get() > 1000000) {
count = new AtomicInteger(new Random().nextInt(100));
} else {
// count++ // count++
Integer count = routeCountEachJob.get(jobId); count.addAndGet(1);
count = (count==null || count>1000000)?(new Random().nextInt(100)):++count; // 初始化时主动Random一次缓解首次压力 }
routeCountEachJob.put(jobId, count); routeCountEachJob.put(jobId, count);
return count; return count.get();
} }
@Override @Override