From 89b07ba350d61733cbf4496c49a49e7dc2029bcd Mon Sep 17 00:00:00 2001 From: Zlatin Balevsky Date: Wed, 29 May 2019 09:19:09 +0100 Subject: [PATCH] download pieces sequentially if over a threshold --- .../groovy/com/muwire/core/download/Pieces.groovy | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/core/src/main/groovy/com/muwire/core/download/Pieces.groovy b/core/src/main/groovy/com/muwire/core/download/Pieces.groovy index eb91169c..64705e32 100644 --- a/core/src/main/groovy/com/muwire/core/download/Pieces.groovy +++ b/core/src/main/groovy/com/muwire/core/download/Pieces.groovy @@ -3,16 +3,29 @@ package com.muwire.core.download class Pieces { private final BitSet bitSet private final int nPieces + private final float ratio private final Random random = new Random() Pieces(int nPieces) { + this(nPieces, 1.0f) + } + + Pieces(int nPieces, float ratio) { this.nPieces = nPieces + this.ratio = ratio bitSet = new BitSet(nPieces) } synchronized int getRandomPiece() { - if (isComplete()) + int cardinality = bitSet.cardinality() + if (cardinality == nPieces) return -1 + + // if fuller than ratio just do sequential + if ( (1.0f * cardinality) / nPieces > ratio) { + return bitSet.nextClearBit(0) + } + while(true) { int start = random.nextInt(nPieces) while(bitSet.get(start) && ++start < nPieces);