Skip to content

Commit

Permalink
GH-4817 LMDB: Make close method of LmdbRecordIterator thread-safe. (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
hmottestad authored Nov 7, 2023
2 parents d81918d + cbeeabb commit 00e6099
Showing 1 changed file with 31 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class LmdbRecordIterator implements RecordIterator {

private final int dbi;

private boolean closed = false;
private volatile boolean closed = false;

private final MDBVal keyData;

Expand All @@ -72,6 +72,8 @@ class LmdbRecordIterator implements RecordIterator {

private final StampedLock txnLock;

private final Thread ownerThread = Thread.currentThread();

LmdbRecordIterator(Pool pool, TripleIndex index, boolean rangeSearch, long subj, long pred, long obj,
long context, boolean explicit, Txn txnRef) throws IOException {
this.pool = pool;
Expand Down Expand Up @@ -140,7 +142,7 @@ public long[] next() throws IOException {
lastResult = mdb_cursor_get(cursor, keyData, valueData, MDB_SET_RANGE);
}
if (lastResult != 0) {
close();
closeInternal(false);
return null;
}
}
Expand Down Expand Up @@ -177,30 +179,45 @@ public long[] next() throws IOException {
return quad;
}
}
close();
closeInternal(false);
return null;
} finally {
txnLock.unlockRead(stamp);
}
}

@Override
public void close() throws IOException {
private void closeInternal(boolean maybeCalledAsync) {
if (!closed) {
long stamp;
if (maybeCalledAsync && ownerThread != Thread.currentThread()) {
stamp = txnLock.writeLock();
} else {
stamp = 0;
}
try {
mdb_cursor_close(cursor);
pool.free(keyData);
pool.free(valueData);
if (minKeyBuf != null) {
pool.free(minKeyBuf);
}
if (maxKey != null) {
pool.free(maxKeyBuf);
pool.free(maxKey);
if (!closed) {
mdb_cursor_close(cursor);
pool.free(keyData);
pool.free(valueData);
if (minKeyBuf != null) {
pool.free(minKeyBuf);
}
if (maxKey != null) {
pool.free(maxKeyBuf);
pool.free(maxKey);
}
}
} finally {
closed = true;
if (stamp != 0) {
txnLock.unlockWrite(stamp);
}
}
}
}

@Override
public void close() throws IOException {
closeInternal(true);
}
}

0 comments on commit 00e6099

Please sign in to comment.