Skip to content

Commit

Permalink
[sdk] Optimize Task memory usage after completion
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
Enet4 committed Jan 9, 2025
1 parent 8a64b37 commit baf31ff
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions sdk/src/main/java/pt/ua/dicoogle/sdk/task/Task.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Type> the return type of the FutureTask
Expand All @@ -32,9 +34,11 @@
*/
public class Task<Type> extends FutureTask<Type> {

private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(Task.class);

private final String uid;
private String taskName;
private Callable callable;
private Callable<Type> callable;
private ArrayList<Runnable> toRunWhenComplete;
private LocalDateTime timeCreated;

Expand All @@ -53,22 +57,31 @@ public Task(String uid, String name, Callable<Type> 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);
}
Expand All @@ -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;
}
Expand Down

0 comments on commit baf31ff

Please sign in to comment.