Java BigInteger占用大量内存

Java BigInteger占用大量内存,java,memory,garbage-collection,biginteger,jconsole,Java,Memory,Garbage Collection,Biginteger,Jconsole,我有以下代码要测试: import java.math.BigInteger; import java.util.Random; public class TestBigInteger { public static void main(String[] args) { BigInteger bigInteger = BigInteger.probablePrime(32, new Random()) .multiply(BigInte

我有以下代码要测试:

import java.math.BigInteger;
import java.util.Random;

public class TestBigInteger {

    public static void main(String[] args) {
        BigInteger bigInteger = BigInteger.probablePrime(32, new Random())
                .multiply(BigInteger.probablePrime(32, new Random()));
        BigInteger n = BigInteger.probablePrime(20, new Random());
        while (!Thread.interrupted()) {
            bigInteger.mod(n);
        }

    }
}
我从jconsole中得到了以下曲线图:


为什么会这样?如果my
bigInteger
的长度只有64位,为什么mod操作会占用大量内存?

这不是保留大量内存,而是产生大量垃圾

    while (!Thread.interrupted()) {
        bigInteger.mod(n); // create a new objects each time.
    }
这个循环以尽可能快的速度创建垃圾(还需要一点CPU工作),因此您应该看到内存使用非常活跃

如果我的bigInteger只有64位长度,为什么mod操作占用了大量内存

这使得内存使用率更高,因为执行计算所花费的实际CPU量相对较小。如果您有一个更大的数字,那么与创建对象相比,它将花费更多的时间来使用CPU。与它使用的CPU相比,它花费更多的时间来创建垃圾


顺便说一句,我建议您使用来自Java 6的VisualVM和来自Java 7的Java任务控制,而不是jconsole。

函数
biginger。mod
使用的函数创建的
可变biginger
对象很少

您通过调用以下命令创建了许多对象:

 while (!Thread.interrupted()) {
        bigInteger.mod(n); // create a new large object each time.
 }

因为垃圾收集器不会在每个对象之后运行,它会在内存达到某个阈值时运行,然后清除所有旧引用。好吧,它正在创建垃圾
biginger.mod()
创建了几个您刚刚扔掉的对象。但是你可以看到GC每隔一段时间就会收到垃圾。为什么你说BigInteger是8字节?作为对象,它至少有12个字节的头和信息。我不知道BigInteger的内部结构,但我认为它远不止8字节的信息。此外,对象排列为8的倍数。。所以真的不可能是64岁bit@Jack,我的意思是bigInteger是两个32位数字的乘积。所以我假设bigInteger是64位的。在我注意到数字是“64位”后,我更改了我的注释;)好的,我注意到:)