【发布时间】:2020-01-22 08:50:39
【问题描述】:
遇到一个使用此代码的项目:
public class IndexUpdater implements Runnable {
@Override
public void run() {
final AtomicInteger count = new AtomicInteger(0);
FindIterable<Document> iterable = mongoService.getDocuments(entryMeta, null, "guid");
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
count.incrementAndGet();
// A lot of code....
if (count.get() / 100 * 100 == count.get()) {
LOG.info(String.format("Processing: %s", count.get()));
}
}
});
}
}
这里我对三行代码感兴趣:
if (count.get() / 100 * 100 == count.get()) {
LOG.info(String.format("Processing: %s", count.get()));
}
考虑到多线程和 AtomicInteger 变量的类型,这种情况是否有意义?或者这是一个毫无意义的检查? 有趣的是,IntellijIdea 并没有强调这种结构毫无意义。
【问题讨论】:
-
我不明白
count.get() / 100 * 100 == count.get()应该完成什么。你只是想检查count.get()%100==0吗? -
在两次调用中,
count.get()的值并不总是相同。使用count.get() % 100 == 0会更容易。 -
考虑到“编写满足您需要的代码”的做法是没有意义的:它向下舍入到最接近的 100,然后打印四舍五入的数字是否是原始数字,所以.. . 为什么不打印
count % 100 == 0,这是测试倍数的标准方法? -
考虑多线程:这里有多线程吗? forEach 真的在多个线程上执行 Block 吗?
-
“有趣的是,IntellijIdea 并没有强调这种结构毫无意义” Intellij 无法确定任意代码的意义。它只会标记“已知”模式。
标签: java multithreading java.util.concurrent atomicinteger