"一个ForkJoinPool是以一个给定的目标并行度级别来构造的;默认情况下,等于可用处理器的数量。"
假设我的CPU有2个核。那么,ForkJoinPool创建的最大线程数是4?
假设我正在执行一个异步操作,该操作在循环中返回一个未来的对象(比如10k)操作,该操作使用默认的Forkpool......那么,Forkpool将创建多少个线程?
List<ListenableFuture<SendResult<String, String>>> cf = new ArrayList<ListenableFuture<SendResult<String, String>>>();
future = kafkaTemplate.send(topicName, message);
cf.add(future);
i++;
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
syso("sent success");
}
@Override
public void onFailure(Throwable ex) {
System.out.println(" sending failed");
}
});
而且,在其他一些类中,我正在检查所有的future是否已经完成。
for (ListenableFuture<SendResult<String, String>> m : myFutures) {
m.get();
}
没有额外的线程,期货是在生产者的IO线程上完成的。
下面是一个显示回调的测试......
@SpringBootApplication
public class So61415751Application {
private static final Logger LOG = LoggerFactory.getLogger(So61415751Application.class);
public static void main(String[] args) {
SpringApplication.run(So61415751Application.class, args);
}
@Bean
public ApplicationRunner runner(KafkaTemplate<String, String> template) {
template.setProducerListener(new ProducerListener<String, String>() {
@Override
public void onSuccess(ProducerRecord<String, String> producerRecord, RecordMetadata recordMetadata) {
LOG.info(recordMetadata.toString());
}
});
return args -> {
IntStream.range(0, 9).forEach(i -> template.send("so61415751", "foo" + i));
LOG.info("Sent");
Thread.sleep(10_000);
};
}
@Bean
public NewTopic topic() {
return TopicBuilder.name("so61415751").partitions(1).replicas(1).build();
}
}
spring.kafka.producer.properties.linger.ms=3000
#logging.level.org.springframework.kafka=debug
logging.level.org.apache.kafka=debug
结果
2020-04-24 17:27:46.282 INFO 96084 --- [ main] com.example.demo.So61415751Application : Sent
...
3 second linger
...
2020-04-24 17:27:49.299 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@63
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@64
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@65
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@66
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@67
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@68
2020-04-24 17:27:49.300 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@69
2020-04-24 17:27:49.301 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@70
2020-04-24 17:27:49.301 INFO 96084 --- [ad | producer-1] com.example.demo.So61415751Application : so61415751-0@71
(调用的线程是 ProducerListener
也完成了未来)。)