From baf31ff3c554091cb7d4f02dcb15dab51b370b7f Mon Sep 17 00:00:00 2001 From: Eduardo Pinho Date: Thu, 9 Jan 2025 12:28:36 +0000 Subject: [PATCH] [sdk] Optimize Task memory usage after completion - when the task is done, remove references to callable and complete hooks so that the GC can sweep them - add try-catch safeguard around completion hook calls - reduce default capabity of toRunWhenComplete (usually only 1 or 2 hooks are employed) - use protected method done() instead of set(V) for calling complete hooks as well as the clean-up - no raw types --- .../java/pt/ua/dicoogle/sdk/task/Task.java | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/sdk/src/main/java/pt/ua/dicoogle/sdk/task/Task.java b/sdk/src/main/java/pt/ua/dicoogle/sdk/task/Task.java index e71df5c3e..87e04620c 100644 --- a/sdk/src/main/java/pt/ua/dicoogle/sdk/task/Task.java +++ b/sdk/src/main/java/pt/ua/dicoogle/sdk/task/Task.java @@ -24,6 +24,8 @@ import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; +import org.slf4j.Logger; + /** An entity for describing an asynchronous task in Dicoogle. * * @param the return type of the FutureTask @@ -32,9 +34,11 @@ */ public class Task extends FutureTask { + private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(Task.class); + private final String uid; private String taskName; - private Callable callable; + private Callable callable; private ArrayList toRunWhenComplete; private LocalDateTime timeCreated; @@ -53,22 +57,31 @@ public Task(String uid, String name, Callable c) { this.callable = c; this.uid = uid; taskName = name; - toRunWhenComplete = new ArrayList<>(); + toRunWhenComplete = new ArrayList<>(2); this.timeCreated = LocalDateTime.now(); } + /** When the task is done, run the runnables registered + * then clean up references to reduce footprint. + */ @Override - protected void set(Type ret) { - super.set(ret); - for (Runnable r : toRunWhenComplete) { - r.run(); + protected void done() { + for (Runnable r : this.toRunWhenComplete) { + try { + r.run(); + } catch (Exception ex) { + LOG.warn("Error running task completion hook", ex); + } } + this.toRunWhenComplete.clear(); + this.callable = null; } public String getUid() { return uid; } + /** Add a completion hook to this task. */ public void onCompletion(Runnable r) { toRunWhenComplete.add(r); } @@ -92,7 +105,7 @@ public void setName(String name) { */ public float getProgress() { if (callable instanceof ProgressCallable) { - return ((ProgressCallable) this.callable).getProgress(); + return ((ProgressCallable) this.callable).getProgress(); } return -1; }