gpt4 book ai didi

java - Logger.getLogger 行为不一致,取决于变量是否内联

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:00 24 4
gpt4 key购买 nike

稍后编辑:(为什么我认为这与 here 的情况不同)

所有操作都在一个实例方法中完成,进进出出,我处理的每个文件一次。我提取的本地字段(而不是内联)没有在其他任何地方使用,所以 GC 在迭代后无论如何都会清除它......

--

在标准的 J2SE 应用程序中(main 方法从 Eclipse 运行),同时使用 apache pdfboxpdf2dom 进行一些 pdf 到 html 的转换,我想清除一些不需要的 INFO 日志条目。

意外情况:

这段代码每次都能正常工作:

    Logger logger = Logger.getLogger("org.mabb.fontverter.opentype.TtfInstructions.TtfInstructionParser");
logger.setLevel(Level.WARNING);

但是,如果我内联 logger 变量,它就会开始出现意外行为:

Logger.getLogger("org.mabb.fontverter.opentype.TtfInstructions.TtfInstructionParser").setLevel(Level.WARNING);

在第二种情况下,记录器上的更改仅在允许经过一小段时间间隔后才生效:

  • 要么我调试并花几秒钟检查线路
  • 或者如果我处理多个 pdf 文件,这意味着整个执行过程需要稍长的时间...

这是什么原因?

谢谢。

最佳答案

简而言之,添加本地引用足以延长对象的生命周期。

Oracle 的 Vladimir Ivanov 在 [PATCH] Reduce Chance Of Mistakenly Early Backing Memory Cleanup 中解释了这一点在 OpenJDK 核心库邮件列表中:

JIT-compilers in HotSpot aggressively prune dead locals, but they do that based on method bytecode analysis (and not on optimized IR). So, any usage of a local extends its live range, even if that usage is eliminated in generated code. It means an oop in that local will live past its last usage in generated code and all safepoints (in generated code) till last usage (on bytecode level) will enumerate the local it is held in.

If there were GC-only safepoints supported, then JITs could still prune unused locals from oop maps, but HotSpot doesn't have them and all safepoints in generated code keep full JVM state, so it's always possible to deoptimize at any one of them (and then run into the code which is eliminated in generated code).

If there are no safepoints till the end of the method, then nothing will keep the object alive. But there's no way for GC to collect it, since GCs rely on safepoints to mark thread stack. (That's why I mentioned GC-only safepoints earlier.)

因此,只要本地 ref 延长记录器对象的生命周期,使得 Logger.getLogger 返回由本地 var 创建和持有的记录器,它就可以正常工作。

对于日志记录,不要使用方法本地引用。而是将对记录器的引用保存在 wider scope 中并最好在记录器开始发布记录之前设置一次级别。

关于java - Logger.getLogger 行为不一致,取决于变量是否内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com