Skip to content

Commit 2ea6c77

Browse files
committed
Synchronize on cache file
1 parent 96b2ffe commit 2ea6c77

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

core/src/main/java/xyz/gianlu/librespot/cache/CacheManager.java

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,9 @@ public byte[] getHeader(byte id) throws SQLException {
229229
public boolean hasChunk(int index) throws SQLException, IOException {
230230
updateTimestamp();
231231

232-
if (io.length() < (index + 1) * CHUNK_SIZE) return false;
232+
synchronized (io) {
233+
if (io.length() < (index + 1) * CHUNK_SIZE) return false;
234+
}
233235

234236
try (PreparedStatement statement = table.prepareStatement("SELECT available FROM Chunks WHERE fileId=? AND chunkIndex=? LIMIT 1")) {
235237
statement.setString(1, Utils.bytesToHex(fileId));
@@ -249,19 +251,23 @@ public void readChunk(int index, @NotNull GeneralWritableStream stream) throws I
249251
public byte[] readChunk(int index) throws IOException {
250252
updateTimestamp();
251253

252-
io.seek(index * CHUNK_SIZE);
254+
synchronized (io) {
255+
io.seek(index * CHUNK_SIZE);
253256

254-
byte[] buffer = new byte[CHUNK_SIZE];
255-
int read = io.read(buffer);
256-
if (read != buffer.length)
257-
throw new IOException(String.format("Couldn't read full chunk, read: %d, needed: %d", read, buffer.length));
257+
byte[] buffer = new byte[CHUNK_SIZE];
258+
int read = io.read(buffer);
259+
if (read != buffer.length)
260+
throw new IOException(String.format("Couldn't read full chunk, read: %d, needed: %d", read, buffer.length));
258261

259-
return buffer;
262+
return buffer;
263+
}
260264
}
261265

262266
public void writeChunk(byte[] buffer, int index) throws IOException, SQLException {
263-
io.seek(index * CHUNK_SIZE);
264-
io.write(buffer);
267+
synchronized (io) {
268+
io.seek(index * CHUNK_SIZE);
269+
io.write(buffer);
270+
}
265271

266272
try (PreparedStatement statement = table.prepareStatement("INSERT OR REPLACE INTO Chunks (fileId, chunkIndex, available) VALUES (?, ?, ?)")) {
267273
statement.setString(1, Utils.bytesToHex(fileId));
@@ -276,8 +282,10 @@ public void writeChunk(byte[] buffer, int index) throws IOException, SQLExceptio
276282

277283
@Override
278284
public void close() throws IOException {
279-
io.close();
280285
handlers.remove(fileId);
286+
synchronized (io) {
287+
io.close();
288+
}
281289
}
282290
}
283291
}

0 commit comments

Comments
 (0)