Java 哈希映射内存使用

Java 哈希映射内存使用,java,memory,hashmap,Java,Memory,Hashmap,我创建了一个哈希映射,它基本上是嵌套哈希映射的集合:- Map<String, Map<KeyPOJO,ValuesPOJO>> customMap= new HashMap<String, Map<KeyPOJO,ValuesPOJO>>(); 我将在其中插入10000条记录,并希望确定其内存使用情况,即在满10000条记录后的内存大小 请告诉我如何在不使用分析工具和第三方库的情况下通过程序获得这些信息 要确定其内存使用情况,即内存大小 调用-

我创建了一个哈希映射,它基本上是嵌套哈希映射的集合:-

Map<String, Map<KeyPOJO,ValuesPOJO>> customMap= new HashMap<String, Map<KeyPOJO,ValuesPOJO>>();
我将在其中插入10000条记录,并希望确定其内存使用情况,即在满10000条记录后的内存大小

请告诉我如何在不使用分析工具和第三方库的情况下通过程序获得这些信息

要确定其内存使用情况,即内存大小

调用-创建和填充地图之前和之后

要确定其内存使用情况,即内存大小


调用-在创建和填充映射之前和之后。

如果您只想知道JVM中使用了多少内存,以及有多少可用内存,您可以尝试以下方法:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

如果您只想知道JVM中使用了多少内存,有多少是可用的,您可以尝试以下方法:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

这不会给出哈希映射的确切内存使用情况,它还将包括中间POJO、变量、迭代器等的内存。。我需要的是哈希映射占用的内存only@TimothyDrisdelle是的,这是真的,只要这些对象有引用,因此不能被垃圾收集。所以Runtime.getRuntime.totalMemory对我不起作用:@TimothyDrisdelle你能做的是,像你已经做的那样创建和填充你的映射,然后调用totalMemory,创建一个新映射并将第一个映射的内容复制到此新映射,然后再次调用totalMemory。不能轻松使用totalMemory技术还有一个更严重的原因:线程本地分配缓冲区。单个对象的分配可能会在totalMemory FreeMemory上留下8K的内存占用,这不会给出哈希映射的确切内存使用情况,它还将包括中间POJO、变量、迭代器等的内存。。我需要的是哈希映射占用的内存only@TimothyDrisdelle是的,这是真的,只要这些对象有引用,因此不能被垃圾收集。所以Runtime.getRuntime.totalMemory对我不起作用:@TimothyDrisdelle你能做的是,像你已经做的那样创建和填充你的映射,然后调用totalMemory,创建一个新映射并将第一个映射的内容复制到此新映射,然后再次调用totalMemory。不能轻松使用totalMemory技术还有一个更严重的原因:线程本地分配缓冲区。单个对象的分配会在totalMemory freeMemory上留下8K的内存占用