3 import java.util.concurrent.Executors;
4 import java.util.concurrent.ScheduledExecutorService;
5 import java.util.concurrent.TimeUnit;
7 import javax.swing.SwingUtilities;
10 * This class helps to provide a solution in concurrent garbage collection issue
11 * with VTK. This class allow automatic garbage collection done in a specific
12 * thread such as the EDT.
14 * @author sebastien jourdain - sebastien.jourdain@kitware.com
16 public class vtkJavaGarbageCollector {
18 private ScheduledExecutorService executor;
19 private Runnable deleteRunnable;
20 private Runnable deferredEdtRunnable;
21 private long periodTime;
22 private TimeUnit timeUnit;
23 private boolean autoCollectionRunning;
24 private boolean debug;
27 * Build a garbage collector which is configured to garbage collect every
28 * seconds but has not been started yet. The user has to call
29 * SetAutoGarbageCollection(true) to make it start.
31 public vtkJavaGarbageCollector() {
35 timeUnit = TimeUnit.SECONDS;
36 autoCollectionRunning = false;
38 executor = Executors.newSingleThreadScheduledExecutor();
39 deleteRunnable = new Runnable() {
43 vtkReferenceInformation info = vtkObjectBase.JAVA_OBJECT_MANAGER.gc(debug);
45 System.out.println(info);
46 System.out.println(info.listKeptReferenceToString());
47 System.out.println(info.listRemovedReferenceToString());
51 deferredEdtRunnable = new Runnable() {
54 SwingUtilities.invokeLater(deleteRunnable);
60 * Set the schedule time that should be used to send a garbage collection
66 public void SetScheduleTime(long period, TimeUnit timeUnit) {
67 this.periodTime = period;
68 this.timeUnit = timeUnit;
69 SetAutoGarbageCollection(autoCollectionRunning);
73 * Whether to print out when garbage collection is run.
77 public void SetDebug(boolean debug) {
82 * Start or stop the automatic garbage collection in the EDT.
84 * @param doGarbageCollectionInEDT
86 public void SetAutoGarbageCollection(boolean doGarbageCollectionInEDT) {
87 autoCollectionRunning = doGarbageCollectionInEDT;
89 if (doGarbageCollectionInEDT) {
90 executor = Executors.newSingleThreadScheduledExecutor();
91 executor.scheduleAtFixedRate(deferredEdtRunnable, periodTime, periodTime, timeUnit);
96 * Shortcut for SetAutoGarbageCollection(true)
97 * @see SetAutoGarbageCollection
100 this.SetAutoGarbageCollection(true);
104 * Shortcut for SetAutoGarbageCollection(false)
105 * @see SetAutoGarbageCollection
108 this.SetAutoGarbageCollection(false);
112 * @return the runnable that do the garbage collection. This could be used
113 * if you want to execute the garbage collection in another thread
116 public Runnable GetDeleteRunnable() {
117 return deleteRunnable;