我们正在使用 java 7 并致力于多线程数据处理应用程序。由于某些限制,我们没有使用 spark 或任何其他 map-reduce 方法来解决这个问题。这个项目的想法是使用多线程最大化应用程序的性能。
我的理解是,在任何给定点,考虑到 CPU 除了操作系统之外没有运行任何其他东西,同时工作的线程数将等于 CPU 提供的超线程数。但是有 java GC 会时不时地启动。我们也必须考虑到这一点。
此外,我知道如果我创建更多线程,那么我实际上会降低性能,因为上下文切换会花费时间。
问题是考虑所有这些因素并创建适当数量的线程的最佳方法是什么。任何想法或思维过程?还有其他我应该考虑的过程吗?
最佳答案
The question is what would be the best way to consider all these things and create appropriate number of threads
我会使用 Java 8 来为您完成这项工作。例如
Results result = listOfWork.parallelStream()
.map(t -> t.doWork())
.collect(Collectors.reduce(.....));
但是,如果您卡在 Java 7 上,则可以使用 ExecutorService。
int procs = Runtime.getRuntime().availableProcessors();
ExecutorService es = Executors.newFixedThreadPool(procs);
But there is java GC which will kick-in every now and then
除非您使用的是 CMS,否则它不会同时启动,因此这些线程在做什么并不重要(就调整您的线程池而言)
Is there any other process that I should consider?
如果您的机器上有其他大量使用 CPU 的进程,您应该考虑它们。
关于java - java线程数>内核数和垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870321/