Skip to content

Commit

Permalink
fix resource leak when request message was received after closing pie…
Browse files Browse the repository at this point in the history
…ce storage
  • Loading branch information
Dead-off committed Jan 16, 2019
1 parent 6e14bf7 commit 8d3dfeb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ private void hashSingleThread() {
public synchronized void close() {
logger.trace("Closing torrent", myTorrentMetadata.getDirectoryName());
try {
this.pieceStorage.close();
this.pieceStorage.closeFully();
isFileChannelOpen = false;
} catch (IOException ioe) {
logger.error("Error closing torrent byte storage: {}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ public interface PieceStorage extends Closeable {

boolean isFinished();

void closeFully() throws IOException;

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class PieceStorageImpl implements PieceStorage {
private final int piecesCount;
private final int pieceSize;
private volatile boolean isOpen;
private volatile boolean closedFully = false;

public PieceStorageImpl(TorrentByteStorage fileCollectionStorage,
BitSet availablePieces,
Expand Down Expand Up @@ -49,6 +50,8 @@ public void savePiece(int pieceIndex, byte[] pieceData) throws IOException {
try {
readWriteLock.writeLock().lock();

if (closedFully) throw new IOException("Storage is closed");

BitSet availablePieces = this.availablePieces;

boolean isFullyDownloaded = availablePieces == null;
Expand Down Expand Up @@ -90,6 +93,8 @@ public byte[] readPiecePart(int pieceIndex, int offset, int length) throws IOExc
try {
readWriteLock.readLock().lock();

if (closedFully) throw new IOException("Storage is closed");

BitSet availablePieces = this.availablePieces;
if (availablePieces != null && !availablePieces.get(pieceIndex)) {
throw new IllegalArgumentException("trying reading part of not available piece");
Expand Down Expand Up @@ -119,6 +124,17 @@ public boolean isFinished() {
}
}

@Override
public void closeFully() throws IOException {
try {
readWriteLock.writeLock().lock();
close0();
closedFully = true;
} finally {
readWriteLock.writeLock().unlock();
}
}

@Override
public BitSet getAvailablePieces() {
try {
Expand All @@ -143,11 +159,15 @@ public BitSet getAvailablePieces() {
public void close() throws IOException {
try {
readWriteLock.writeLock().lock();
if (!isOpen) return;
fileCollectionStorage.close();
isOpen = false;
close0();
} finally {
readWriteLock.writeLock().unlock();
}
}

private void close0() throws IOException {
if (!isOpen) return;
fileCollectionStorage.close();
isOpen = false;
}
}

0 comments on commit 8d3dfeb

Please sign in to comment.