package io.dropwizard.servlets.tasks;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
public class GarbageCollectionTask extends Task {
private final Runtime runtime;
public GarbageCollectionTask() {
this(Runtime.getRuntime());
}
public GarbageCollectionTask(Runtime runtime) {
super("gc");
this.runtime = runtime;
}
@Override
@SuppressWarnings("CallToSystemGC")
public void execute(Map<String, List<String>> parameters, PrintWriter output) {
final int count = parseRuns(parameters);
for (int i = 0; i < count; i++) {
output.println("Running GC...");
output.flush();
runtime.gc();
}
output.println("Done!");
}
private static int parseRuns(Map<String, List<String>> parameters) {
final List<String> runs = parameters.get("runs");
if (runs == null || runs.isEmpty()) {
return 1;
} else {
try {
return Integer.parseInt(runs.get(0));
} catch (NumberFormatException ignored) {
return 1;
}
}
}
}