Skip to content

Commit c38b4de

Browse files
authored
[Serialiser] Fix some inputs sometimes not being saved (#245)
Fixed a race condition in the FileThread that prevents some inputs at the end of the file not getting serialised. Switched the collection type from an arraylist to a queue and added an extra safety writeOutput, after the thread is closed
2 parents 31b85f3 + 4f76386 commit c38b4de

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

src/main/java/com/minecrafttas/tasmod/util/FileThread.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
import java.nio.file.Files;
99
import java.nio.file.Path;
1010
import java.nio.file.StandardOpenOption;
11-
import java.util.ArrayList;
12-
import java.util.List;
11+
import java.util.concurrent.ConcurrentLinkedQueue;
1312

1413
/**
1514
* Thread for writing files to disc
@@ -21,34 +20,35 @@ public class FileThread extends Thread {
2120
private final PrintWriter stream;
2221
private boolean end = false;
2322

24-
private final List<String> output = new ArrayList<>();
23+
private final ConcurrentLinkedQueue<String> output = new ConcurrentLinkedQueue<>();
2524

2625
public FileThread(Path fileLocation, boolean append) throws IOException {
26+
super("TASmod FileWriter Thread");
2727
OutputStream outStream = Files.newOutputStream(fileLocation, StandardOpenOption.CREATE, append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING);
28-
stream = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
28+
stream = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8), true);
2929
}
3030

3131
public void addLine(String line) {
32-
synchronized (output) {
33-
output.add(line + "\n");
34-
}
32+
output.add(line + "\n");
3533
}
3634

3735
@Override
3836
public void run() {
3937
while (!end) {
40-
synchronized (output) {
41-
ArrayList<String> newList = new ArrayList<String>(output);
42-
output.clear();
43-
for (String line : newList) {
44-
stream.print(line);
45-
}
46-
}
38+
writeOutput();
4739
}
40+
writeOutput(); // Print any remaining lines, just to be safe...
41+
4842
stream.flush();
4943
stream.close();
5044
}
5145

46+
private void writeOutput() {
47+
String line;
48+
while ((line = output.poll()) != null)
49+
stream.print(line);
50+
}
51+
5252
public void close() {
5353
end = true;
5454
}

0 commit comments

Comments
 (0)