【问题标题】:How to lazy correctly initialize a static array field in Java如何在Java中正确初始化静态数组字段
【发布时间】:2021-08-05 21:34:39
【问题描述】:

生成的 Antlr4 词法分析器和解析器有一些内部数据放在堆上,在解析后我想释放这些数据以清除堆空间并防止内存溢出。我正在使用惰性初始化器来执行此操作,然后将它们删除。其中大部分都很容易做到。

但是,当我这样做时,有一个数组在抱怨。我需要知道正确的习惯用法。我只有一个线程(而且我只使用过一次词法分析器/解析器(*除了在测试中,见下文))所以我并不真正关心同步,但我希望有警告/lint free 编译,并且“ findBugs" 不喜欢我使用的代码。

这是我尝试的初始代码:

public class Lexer;
    protected static DFA[] = null; 
...
    public Lexer(CharStream input) {
       if (_decisionToDFA == null) {
          _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
          for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
              _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
          }
        }
    }
...
    public void closeLexer() {
       _decisionToDFA = null;
    }

中间尝试进行静态初始化的代码是 FindBugs 抱怨的代码。我尝试了以下方法,但没有帮助。

       if (_decisionToDFA == null) {
          // build it here locally
          DFA _local_decisionToDFA[] = new DFA[_ATN.getNumberOfDecisions()];
          for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
              _local_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
          }
        _decisionToDFA = _local_decisionToDFA;  // then just move the reference
        }

*下面:

运行单元测试时例外。目前只有 2k 多一点的单元测试,每个测试都会解析一些代码片段,然后遍历生成的解析树并计算一些东西并检查计算是否匹配正确的语义。

不幸的是,词法分析器和解析器为此构建的内部数据(例如,这些数组和一些缓存等)会慢慢累积并最终耗尽所有堆空间,导致接近尾声的测试耗尽内存,这就是为什么我需要释放它们。在生产运行中,每次编译都是一个独立的进程,有自己的地址空间,所以问题不大。

Description Resource    Path    Location    Type
Incorrect lazy initialization and update of static field Lexer._decisionToDFA in new Lexer(CharStream) [Scary(6), High confidence]  PowerShellLexer.java    /src/main/java/Lexer    line 413    FindBugs Problem (Scary)

【问题讨论】:

  • "protected static DFA[] = null; " - 这对我来说像是一个语法错误。 --- "and "findBugs" 不喜欢我使用的代码。" - findbugs 到底说了什么?
  • 根据this question,findbugs 可能确实指的是潜在的线程问题。但是,如果没有 findbugs 的更详细解释,很难说出 findbugs 到底指的是什么。

标签: java arrays static lazy-initialization


【解决方案1】:

事实证明,如果您将代码放入函数中,这似乎可以消除 findBugs 错误消息。

public class Lexer;
    protected static DFA[] = null; 
...
    private DFA[] createDecisionToDFA() {
          // build it here locally
          DFA _local_decisionToDFA[] = new DFA[_ATN.getNumberOfDecisions()];
          for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
              _local_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
          }
        return _local_decisionToDFA;  // then just move the reference
        }

    public Lexer(CharStream input) {
       if (_decisionToDFA == null) {
          _decisionToDFA = createDecisionToDFA();
        }
    }
...
    public void closeLexer() {
       _decisionToDFA = null;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2011-02-15
    相关资源
    最近更新 更多