简体   繁体   English

如何在某些代码执行之间禁用 GC 或获取 GC 暂停时间?

[英]How to disable GC or get GC pause time between some code execution?

I read a article before that FGC influenced timing and made application produce wrong result.之前看过一篇文章说FGC影响时序导致应用程序产生错误的结果。
The code example is like:代码示例如下:

long start = System.currentTimeInMillis();
doSomething();
// what if here comes a long time FGC pause
long end = System.currentTimeInMillis();
if (end - start > TIME_OUT) {
    xxxx
}

if GC happens between start and end assignment,the time will be more than the actual value it is and affect the result.如果 GC 发生在startend分配之间,时间将超过它的实际值并影响结果。

There are some ways to fix.有一些方法可以解决。
One way is to disable GC between them,I know it's impossible to disable GC a while now.I want to know if there any way to remove safepoint between some code(or to refactor the code to achieve it?).一种方法是禁用它们之间的 GC,我知道暂时禁用 GC 是不可能的。我想知道是否有任何方法可以删除safepoint代码之间的安全点(或重构代码以实现它?)。

The other is to get GC pause time, seems (maybe) not harder than the first way.另一种是获取 GC 暂停时间,似乎(也许)并不比第一种方法难。

Back to the question:回到问题:
If I have a time sensitive logic, how can I avoid it to be affected by GC?如果我有一个时间敏感的逻辑,我怎样才能避免它被 GC 影响?

You can do few things here (in increasing order of difficulty and you can combine some of these):你可以在这里做一些事情(按难度递增的顺序,你可以结合其中的一些):

  1. Run your tests with as big heap as you can muster (it will work only if you can avoid any GC; as soon as you hit GC, it will be a long pause).使用尽可能大的堆运行测试(只有当你可以避免任何 GC 时它才会工作;一旦你命中 GC,它将是一个长时间的暂停)。

  2. Use better timing than wall clock.使用比挂钟更好的时间。 See Java Microbenchmark Harness参见Java Microbenchmark Harness

  3. Use many runs to average impact of any GC out by removing the top outliers.使用多次运行通过移除最高异常值来平均任何 GC 的影响。 JMH from point above helps here.上面的 JMH 在这里有所帮助。

  4. Ask your JVM how long it spent GC using MX Beans .问你的 JVM GC 使用MX Beans花了多长时间。 YMMV depending on JVM. YMMV 取决于 JVM。

  5. Log all GC pauses into GC log and use these in calculation将所有 GC 暂停记录到 GC 日志中并在计算中使用这些

  6. Modify your code to do no allocations in the critical section (see this or this article for some tips)修改您的代码以在关键部分不进行分配(有关一些提示,请参阅 本文本文

  7. Azul Systems's JVM called ZING has pauseless GC . Azul Systems 的 JVM 称为ZING 具有无间断 GC This will cost money.这会花钱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM