简体   繁体   English

Java堆多线程优化

[英]Java Heap Multithreading Optimization

I am writing a Java program that runs many simulations simultaneously in different threads and averages the results together. 我正在编写一个Java程序,该程序在不同的线程中同时运行许多模拟,并将结果平均在一起。 I want to run a lot of simulations, more than can be running simultaneously, so I want to run as many as I can simultaneously without running out of memory and “queue” the rest. 我想运行许多模拟,而不是同时运行,因此我想同时运行尽可能多的模拟,而不会耗尽内存并使其余部分“排队”。

Is there an easy way to determine the maximum heap memory a thread uses? 有没有一种简单的方法来确定线程使用的最大堆内存?

Is there an easy way to check how much heap memory is being used at run time so I can only start new threads when memory opens up? 有没有一种简单的方法来检查运行时正在使用多少堆内存,因此我只能在内存打开时启动新线程?

PS: I'm new to optimizing multithreaded applications. PS:我是优化多线程应用程序的新手。

Profile your threads to determine how much heap is occupied. 分析您的线程,以确定占用了多少堆。 I know of no way to do this programmatically. 我不知道以编程方式执行此操作。

Don't use more threads than you have cores. 使用的线程不要超过核心数量。 Creating new threads is a relatively expensive operation, and creating too many threads can actually cause your application to run more slowly. 创建新线程是一项相对昂贵的操作,而创建太多线程实际上可能导致您的应用程序运行更慢。 If you're processing huge data, or need very low latency, you'll really want to avoid creating many threads. 如果您正在处理大量数据,或者需要非常低的延迟,那么您确实要避免创建许多线程。

I suggest looking into ExecutorService . 我建议研究ExecutorService Create a fixed thread pool equal to the number of cores on your simulation machine. 创建一个与模拟计算机上的内核数相等的固定线程池。

Edit: 编辑:

Since Java 1.4 we've had this available: 从Java 1.4开始,我们提供了以下功能:

int cores = Runtime.getRuntime().availableProcessors();

Try this, create a fixed thread pool with cores threads. 试试这个,用cores线程创建一个固定的线程池。 This would allow your application to scale between machines with a difference in cores. 这将使您的应用程序可以在内核不同的机器之间扩展。

Note this is the number of logical cores, so with Intel's hyperthreading feature it would count 2 "cores" for every processor. 请注意,这是逻辑核心的数量,因此,借助英特尔的超线程功能,每个处理器将计为2个“核心”。 Still, a good measurement. 仍然是一个很好的衡量。

You can run the program with a single thread while monitoring it in VisualVM , and then with two threads, then with three. VisualVM中监视程序时,可以使用一个线程运行该程序,然后可以使用两个线程,然后使用三个线程。 The difference in memory usage and garbage collection frequency can give you an idea of how much heap memory a single thread uses and how much of the memory is taken by objects shared between different threads. 内存使用率和垃圾回收频率的差异可以使您了解单个线程使用多少堆内存,以及不同线程之间共享的对象占用了多少内存。

This is not an "easy" task to do, but there are some ways to do it. 这不是一件容易的事,但是有一些方法可以做到。 The jvm exposes the current memory usage through the management apis. jvm通过管理API公开当前的内存使用情况。 You can use the MemoryMXBean and the MemoryPoolMXBean to get access to the current jvm memory status. 您可以使用MemoryMXBean和MemoryPoolMXBean来访问当前的jvm内存状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM