为什么这个Java方法会泄漏 - 为什么内联它会修复泄漏?

Bil*_*ham 5 java garbage-collection memory-management clojure sequence

我写了一个最小的some-lazy(int)序列类GarbageTest.java,作为一个实验,看看我是否可以在Clojure中以Java的方式处理非常长的懒惰序列.

给定一个naturals()返回惰性无限序列自然数的方法; 一个drop(n,sequence)那滴的第一个方法n的要素sequence,并返回的其余部分sequence; 和一个nth(n,sequence)简单返回的方法:drop(n, lazySeq).head(),我写了两个测试:

static int N = (int)1e6;

// succeeds @ N = (int)1e8 with java -Xmx10m
@Test
public void dropTest() {
    assertThat( drop(N, naturals()).head(), is(N+1));
}

// fails with OutOfMemoryError @ N = (int)1e6 with java -Xmx10m
@Test
public void nthTest() {
    assertThat( nth(N, naturals()), is(N+1));
}
Run Code Online (Sandbox Code Playgroud)

请注意,dropTest()通过复制主体nthTest()然后在调用上调用IntelliJ的"内联"重构来生成主体nth(N, naturals()).所以在我看来,行为dropTest()应该与行为相同nthTest().

但它不完全相同!dropTest()运行,以用N完成高达而1E8 nthTest()失败,OutOfMemoryError对于N小1E6.

我避免内心阶级.我已经尝试了我的代码ClearingArgsGarbageTest.java的变种,它在调用其他方法之前使方法参数为空.我已经应用了YourKit分析器.我查看了字节码.我只是找不到导致nthTest()失败的泄漏.

哪里是"泄漏"?为什么没有nthTest()泄漏dropTest()呢?

如果你不想点击Github项目,这里是GarbageTest.java的其余代码:

/**
 * a not-perfectly-lazy lazy sequence of ints. see LazierGarbageTest for a lazier one
 */
static class LazyishSeq {
    final int head;

    volatile Supplier<LazyishSeq> tailThunk;
    LazyishSeq tailValue;

    LazyishSeq(final int head, final Supplier<LazyishSeq> tailThunk) {
        this.head = head;
        this.tailThunk = tailThunk;
        tailValue = null;
    }

    int head() {
        return head;
    }

    LazyishSeq tail() {
        if (null != tailThunk)
            synchronized(this) {
                if (null != tailThunk) {
                    tailValue = tailThunk.get();
                    tailThunk = null;
                }
            }
        return tailValue;
    }
}

static class Incrementing implements Supplier<LazyishSeq> {
    final int seed;
    private Incrementing(final int seed) { this.seed = seed;}

    public static LazyishSeq createSequence(final int n) {
        return new LazyishSeq( n, new Incrementing(n+1));
    }

    @Override
    public LazyishSeq get() {
        return createSequence(seed);
    }
}

static LazyishSeq naturals() {
    return Incrementing.createSequence(1);
}

static LazyishSeq drop(
        final int n,
        final LazyishSeq lazySeqArg) {
    LazyishSeq lazySeq = lazySeqArg;
    for( int i = n; i > 0 && null != lazySeq; i -= 1) {
        lazySeq = lazySeq.tail();
    }
    return lazySeq;
}

static int nth(final int n, final LazyishSeq lazySeq) {
    return drop(n, lazySeq).head();
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 6

在你的方法

static int nth(final int n, final LazyishSeq lazySeq) {
    return drop(n, lazySeq).head();
}
Run Code Online (Sandbox Code Playgroud)

参数变量lazySeq在整个drop操作期间保存对序列的第一个元素的引用.这可以防止整个序列被垃圾收集.

与...对比

public void dropTest() {
    assertThat( drop(N, naturals()).head(), is(N+1));
}
Run Code Online (Sandbox Code Playgroud)

序列的第一个元素由返回naturals()并直接传递给调用drop,因此从操作数堆栈中删除,并且在执行期间不存在drop.

您尝试将参数变量设置为null,即

static int nth(final int n, /*final*/ LazyishSeq lazySeqArg) {
    final LazyishSeq lazySeqLocal = lazySeqArg;
    lazySeqArg = null;
    return drop(n,lazySeqLocal).head();
}
Run Code Online (Sandbox Code Playgroud)

没有帮助,就像现在一样,lazySeqArg变量是null,但它lazySeqLocal保存了对第一个元素的引用.

局部变量通常不会阻止垃圾收集,允许收集其他未使用的对象,但这并不意味着特定的实现能够执行此操作.

对于HotSpot JVM,只有优化的代码才能清除这些未使用的引用.但在这里,nth并不是一个热点,因为重要的事情发生在drop方法中.

这就是为什么在该drop方法中没有出现相同问题的原因,尽管它也保留了对其参数变量中第一个元素的引用.该drop方法包含执行实际工作的循环,因此很可能由JVM进行优化,这可能导致它消除未使用的变量,从而允许收集已处理的序列部分.

有许多因素可能会影响JVM的优化.除了代码的不同形状之外,似乎在未优化阶段期间的快速存储器分配也可能减少优化器的改进.实际上,当我运行时-Xcompile,完全禁止解释执行,两个变体都成功运行,甚至int N = (int)1e9不再是问题.当然,强制编译会增加启动时间.

我不得不承认,我不明白为什么在混合模式下执行的是差很多,我会进一步调查.但一般来说,您必须意识到垃圾收集器的效率取决于实现,因此在一个环境中收集的对象可能会留在另一个环境中.


Mic*_*zyk 5

Clojure实施了一种用于处理这种情况的策略,称之为“本地清算”。编译器中对它的支持使其可以在纯Clojure代码中所需的地方自动启动(除非在编译时被禁用-有时对调试很有用)。Clojure的确在Java运行时的各个地方清除了本地语言,尽管它无疑很麻烦,但它可以在Java库甚至应用程序代码中使用的方式。

在开始介绍Clojure之前,这里是此示例中发生的情况的简短摘要:

  1. nth(int, LazyishSeq)根据drop(int, LazyishSeq)和实施LazyishSeq.head()

  2. nth将其参数传递drop给它们,并且不再对其使用。

  3. drop 可以很容易地实现以避免避免保持传入序列的开头。

这里nth仍然保持其序列参数的开头。运行时可能会丢弃该引用,但不能保证会。

Clojure处理此问题的方法是在将控制权移交给之前明确清除对序列的引用drop。这是通过一个相当巧妙的技巧完成的(从Clojure 1.9.0开始,链接到GitHub上的以下代码片段):

//  clojure/src/jvm/clojure/lang/Util.java

/**
 *   Copyright (c) Rich Hickey. All rights reserved.
 *   The use and distribution terms for this software are covered by the
 *   Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 *   which can be found in the file epl-v10.html at the root of this distribution.
 *   By using this software in any fashion, you are agreeing to be bound by
 *   the terms of this license.
 *   You must not remove this notice, or any other, from this software.
 **/

// … beginning of the file omitted …

// the next line is the 190th in the file as of Clojure 1.9.0
static public Object ret1(Object ret, Object nil){
        return ret;
}

static public ISeq ret1(ISeq ret, Object nil){
        return ret;
}

// …
Run Code Online (Sandbox Code Playgroud)

鉴于以上情况,对dropinside 的调用nth可以更改为

drop(n, ret1(lazySeq, lazySeq = null))
Run Code Online (Sandbox Code Playgroud)

lazySeq = null将控制权转移给ret1; 之前,将其作为表达式进行评估;值是,null并且将lazySeq引用设置为也会产生副作用nullret1到此为止,已经评估了的第一个参数,因此ret1,在其第一个参数中接收对序列的引用,并按预期方式将其返回,然后将该值传递给drop

因此drop接收到lazySeq本地保留的原始值,但是在控制权转移到之前清除了本地本身drop

因此,nth不再停留在序列的开头。