Skip to content

Commit

Permalink
Add shutdown hook when starting sovler and remove it when finished
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] committed Jan 7, 2024
1 parent c7f2b18 commit 9d4320b
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/main/java/de/nqueensfaf/Solver.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ public abstract class Solver {
private Consumer<Solver> initCb, finishCb;
private int solutionsSmallN = 0;
private boolean isSaving = false;

protected Solver() {
private final Thread shutdownHook = new Thread(() -> {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
while (isSaving) {
try {
Expand All @@ -26,7 +25,7 @@ protected Solver() {
}
}
}));
}
});

public abstract long getDuration();
public abstract float getProgress();
Expand Down Expand Up @@ -120,6 +119,9 @@ private Thread backgroundThread(boolean updateConsumer, boolean autoSaver) {
float progress = getProgress() * 100;
float tmpProgress = progress;

if(autoSaver)
Runtime.getRuntime().addShutdownHook(shutdownHook);

while (isRunning() && getProgress() < 1f) {
if(updateConsumer)
onUpdateConsumer.accept(this, getProgress(), getSolutions(), getDuration());
Expand Down Expand Up @@ -151,6 +153,8 @@ else if (progress >= tmpProgress + config().autoSavePercentageStep) {
onUpdateConsumer.accept(this, getProgress(), getSolutions(), getDuration());

if(autoSaver) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);

progress = getProgress() * 100;
if (progress >= 100) {
if (config().autoDeleteEnabled) {
Expand Down

0 comments on commit 9d4320b

Please sign in to comment.