标题翻译
CountDownLatch vs AtomicInteger and some boilerplate
问题
以下是您提供的代码的翻译部分:
可以在这个示例中使用带有同步和volatile特性的AtomicInteger来代替CountDownLatch吗?我有遗漏了什么吗?是否还有其他情况在其中我不能用AtomicInteger替换CountDownLatch?
static void runProducer(final int sendMessageCount) throws InterruptedException {
final Producer<Long, String> producer = createProducer();
long time = System.currentTimeMillis();
final CountDownLatch countDownLatch = new CountDownLatch(sendMessageCount);
try {
for (long index = time; index < time + sendMessageCount; index++) {
final ProducerRecord<Long, String> record =
new ProducerRecord<>(TOPIC, index, "Hello Mom " + index);
producer.send(record, (metadata, exception) -> {
long elapsedTime = System.currentTimeMillis() - time;
if (metadata != null) {
System.out.printf("已发送记录(key=%s value=%s) " +
"元数据(分区=%d, 偏移量=%d) 时间=%d\n",
record.key(), record.value(), metadata.partition(),
metadata.offset(), elapsedTime);
} else {
exception.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await(25, TimeUnit.SECONDS);
} finally {
producer.flush();
producer.close();
}
}
英文翻译
Can I use AtomicInteger (Which is Synchronized and volatile) instead of countdownLatch in this example. Am I missing something? Is there any other scenario where I cannot replace the countdownLatch with an AtomicInteger?
static void runProducer(final int sendMessageCount) throws InterruptedException {
final Producer<Long, String> producer = createProducer();
long time = System.currentTimeMillis();
final CountDownLatch countDownLatch = new CountDownLatch(sendMessageCount);
try {
for (long index = time; index < time + sendMessageCount; index++) {
final ProducerRecord<Long, String> record =
new ProducerRecord<>(TOPIC, index, "Hello Mom " + index);
producer.send(record, (metadata, exception) -> {
long elapsedTime = System.currentTimeMillis() - time;
if (metadata != null) {
System.out.printf("sent record(key=%s value=%s) " +
"meta(partition=%d, offset=%d) time=%d\n",
record.key(), record.value(), metadata.partition(),
metadata.offset(), elapsedTime);
} else {
exception.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await(25, TimeUnit.SECONDS);
}finally {
producer.flush();
producer.close();
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论