我想使用并行流api来读取redis,获取所有项目,并随机抽取10%的项目。但我发现它有时会 random.nextInt(itemCount)
不接受0作为输入。这使我很困惑。
是多线程问题吗?我不知道该怎么办。
代码如下:
private Timer timer = new Timer(); // I start the job in a timer.
private Random rand = new Random();
private List<String> ids = getIds(); // get redis keys.
private ForkJoinPool updateThreadsPool = new ForkJoinPool(32);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
ForkJoinTask<List<List<Item>>> asyncTask = updateThreadsPool.submit(() -> {
return ids.parallelStream().map(id -> getFromRedis(id)).collect(Collectors.toList());
});
int totalNum = 0;
List<Item> totalItems = new ArrayList<>();
try {
totalNum = asyncTask.get().stream().peek(totalItems::addAll)
.reduce(0, (num, list) -> num + list.size(), Integer::sum);
} catch (Exception e) { // do something }
int randIndex = rand.nextInt(totalNum); // this is where it throws exception.
// says that totalNum is zero.
// I'm pretty sure totalItems is not empty, because I print log for that.
// I tried use int totalNum = totalItems.size(), but I got the same problem.
}
}, 1000L, 1000L
);
暂无答案!
目前还没有任何答案,快来回答吧!