Only create one shutdown hook for save files

This commit is contained in:
FlorianMichael 2023-11-27 20:38:21 +01:00
parent c62aa7516c
commit ddec37d8c8
No known key found for this signature in database
GPG Key ID: C2FB87E71C425126
3 changed files with 25 additions and 26 deletions

View File

@ -15,15 +15,6 @@ jobs:
distribution: 'temurin'
java-version: 17
check-latest: true
- name: Cache Dependencies
uses: actions/cache@v3
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Build with Gradle
run: ./gradlew build
- name: Upload Artifacts

View File

@ -45,7 +45,6 @@ public abstract class AbstractSave {
/**
* This method should be called when the file should be initialized.
* It will read the file and call the {@link #read(JsonObject)} method.
* It will also write the file when the program is closed using the {@link #write(JsonObject)}.
*/
public void init() {
if (file.exists()) {
@ -59,24 +58,27 @@ public abstract class AbstractSave {
read(parentNode);
}
}
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
file.delete();
file.createNewFile();
} catch (IOException e) {
ViaFabricPlus.global().getLogger().error("Failed to create file: " + file.getName() + "!");
}
/**
* This method should be called when the file should be saved.
*/
public void save() {
try {
file.delete();
file.createNewFile();
} catch (IOException e) {
ViaFabricPlus.global().getLogger().error("Failed to create file: " + file.getName() + "!");
}
try (final FileWriter fw = new FileWriter(file)) {
final JsonObject parentNode = new JsonObject();
write(parentNode);
fw.write(GSON.toJson(parentNode));
fw.flush();
} catch (IOException e) {
ViaFabricPlus.global().getLogger().error("Failed to write file: " + file.getName() + "!");
}
}));
try (final FileWriter fw = new FileWriter(file)) {
final JsonObject parentNode = new JsonObject();
write(parentNode);
fw.write(GSON.toJson(parentNode));
fw.flush();
} catch (IOException e) {
ViaFabricPlus.global().getLogger().error("Failed to write file: " + file.getName() + "!");
}
}
public abstract void write(final JsonObject object);

View File

@ -44,6 +44,12 @@ public class SaveManager {
for (AbstractSave save : saves) {
save.init();
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
for (AbstractSave save : saves) {
save.save();
}
}));
}
public void add(final AbstractSave... saves) {