1

I have a slotted java system that runs a code every 2 seconds which takes less than 100ms every time it runs. I want to avoid running garbage collection during that 100ms run but run it in the remaining 1.9s where the system is free. Currently garbage collection may run during that 100ms and adds about 100ms more to it which is unacceptable in my case.

The memory usage of program is about 2G and it may create many small objects during that 100ms. I also run it on a multi-core system (4 cores and more).

Masood_mj
  • 1,144
  • 12
  • 25
  • You can not pause the Java GC. GC runs only when the JVM is in short of memory. So I guess you should better try with allocating more memory to the program. – Debobroto Das Nov 11 '13 at 03:43
  • To the close-proposer: What's unclear with this question??? – maaartinus Nov 11 '13 at 06:35
  • Use a server JVM and let the JVM find out by itself what it has to do. Your scenario looks quite simple. – Holger Nov 11 '13 at 08:39

2 Answers2

1

Try -XX:+UseParallelGC and -XX:+UseOldParallelGC to minimize GC pauses. It is designed for multi-gigabyte heaps and runs garbage collection in parallel on separate threads. Its goal is to avoid "stop-the-world" collections and minimize GS pauses.

brettw
  • 10,664
  • 2
  • 42
  • 59
1

This looks like of the few cases when calling System.gc() is useful. There's no guarantee that it helps, but it's surely worth a try.

You could also try a hack I proposed recently. It's a bit more complicated and may backfire.

  • Allocate a lot of memory during the idle period.
  • Do it in such a way that no objects get promoted into the old generation (as GC there is costly).
  • Make sure that the whole allocation can't be optimized away (something like sum += new byte[123456].hashCode() should do)
  • Stop when you've allocated enough to start the GC. This is the tricky part:
    • You could use finalizers (or better ReferenceQueue<PhantomReference>), but there's no guarantee that it gets run soon after the GC
    • You could watch runtime.getFreeMemory, but who knows if it works reliably?
    • You could try the GarbageCollectorMXBean
    • As a last resort, you could use -XX:+UnlockDiagnosticVMOptions -XX:+PrintGC to watch it from the outside

As I said, it's just a hack for the case no sane solution works.

Community
  • 1
  • 1
maaartinus
  • 44,714
  • 32
  • 161
  • 320
  • I used System.gc() plus -XX:MaxGCPauseMillis=1000 option to bound the major GCs suggested by this function. – Masood_mj Nov 11 '13 at 12:22