|
48 | 48 | import java.nio.file.Files; |
49 | 49 | import java.nio.file.LinkOption; |
50 | 50 | import java.nio.file.Path; |
| 51 | +import java.nio.file.StandardCopyOption; |
| 52 | +import java.nio.file.attribute.FileAttribute; |
51 | 53 | import java.util.ArrayList; |
52 | 54 | import java.util.Arrays; |
53 | 55 | import java.util.Collection; |
@@ -85,6 +87,14 @@ public final class GCUtils { |
85 | 87 |
|
86 | 88 | private static final boolean PRESERVE_HEAP_DUMP_ON_FAILURE = Boolean.parseBoolean(System.getProperty(GCUtils.class.getSimpleName() + ".preserveHeapDumpOnFailure", "true")); |
87 | 89 |
|
| 90 | + /** |
| 91 | + * When set, and if the {@link #PRESERVE_HEAP_DUMP_ON_FAILURE} system property is set to |
| 92 | + * {@code true}, {@code GCUtils} relocates the heap dump to the designated folder. The target |
| 93 | + * heap dump file has the pattern {@code gcutils_heapdump_.+\.hprof} as produced by |
| 94 | + * {@link Files#createTempFile(Path, String, String, FileAttribute[])}. |
| 95 | + */ |
| 96 | + private static final String SAVE_HEAP_DUMP_TO = System.getProperty(GCUtils.class.getSimpleName() + ".saveHeapDumpTo"); |
| 97 | + |
88 | 98 | private static final ReachabilityAnalyser<?> analyser = selectAnalyser(); |
89 | 99 |
|
90 | 100 | private GCUtils() { |
@@ -440,9 +450,21 @@ Result analyse(Collection<? extends Reference<?>> references, boolean force, boo |
440 | 450 | JavaClass trackableReferenceClass = heap.getJavaClassByName(HeapDumpAnalyser.class.getName()); |
441 | 451 | ObjectArrayInstance todoArray = (ObjectArrayInstance) trackableReferenceClass.getValueOfStaticField("todo"); |
442 | 452 | List<Instance> instances = todoArray.getValues(); |
443 | | - result = testCollected.apply(new State(collectGCRootPath, preserveHeapDumpIfNonCollectable ? heapDumpFile : null, heap, instances, todoIndexes)); |
| 453 | + Path targetFile = null; |
| 454 | + if (preserveHeapDumpIfNonCollectable) { |
| 455 | + if (SAVE_HEAP_DUMP_TO != null) { |
| 456 | + Path targetFolder = Path.of(SAVE_HEAP_DUMP_TO); |
| 457 | + targetFile = Files.createTempFile(targetFolder, "gcutils_heapdump_", ".hprof"); |
| 458 | + } else { |
| 459 | + targetFile = heapDumpFile; |
| 460 | + } |
| 461 | + } |
| 462 | + result = testCollected.apply(new State(collectGCRootPath, targetFile, heap, instances, todoIndexes)); |
| 463 | + if (targetFile != null && !targetFile.equals(heapDumpFile)) { |
| 464 | + Files.move(heapDumpFile, targetFile, StandardCopyOption.REPLACE_EXISTING); |
| 465 | + } |
444 | 466 | } finally { |
445 | | - if (result == null || result.isCollected() || !preserveHeapDumpIfNonCollectable) { |
| 467 | + if (result == null || result.isCollected() || !preserveHeapDumpIfNonCollectable || SAVE_HEAP_DUMP_TO != null) { |
446 | 468 | delete(tmpDirectory); |
447 | 469 | } |
448 | 470 | } |
|
0 commit comments