-
Notifications
You must be signed in to change notification settings - Fork 997
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
hadoop: use BufferPool for inputstream (#2620)
- Loading branch information
1 parent
bb84127
commit 74a5104
Showing
2 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package io.juicefs.utils; | ||
|
||
import java.lang.ref.WeakReference; | ||
import java.nio.ByteBuffer; | ||
import java.util.Queue; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ConcurrentLinkedQueue; | ||
import java.util.concurrent.ConcurrentMap; | ||
|
||
/** | ||
* thread safe | ||
*/ | ||
public class BufferPool { | ||
|
||
private static final ConcurrentMap<Integer, Queue<WeakReference<ByteBuffer>>> buffersBySize = new ConcurrentHashMap<>(); | ||
|
||
public static ByteBuffer getBuffer(int size) { | ||
Queue<WeakReference<ByteBuffer>> list = buffersBySize.get(size); | ||
if (list == null) { | ||
return ByteBuffer.allocate(size); | ||
} | ||
|
||
WeakReference<ByteBuffer> ref; | ||
while ((ref = list.poll()) != null) { | ||
ByteBuffer b = ref.get(); | ||
if (b != null) { | ||
return b; | ||
} | ||
} | ||
|
||
return ByteBuffer.allocate(size); | ||
} | ||
|
||
public static void returnBuffer(ByteBuffer buf) { | ||
buf.clear(); | ||
int size = buf.capacity(); | ||
Queue<WeakReference<ByteBuffer>> list = buffersBySize.get(size); | ||
if (list == null) { | ||
list = new ConcurrentLinkedQueue<>(); | ||
Queue<WeakReference<ByteBuffer>> prev = buffersBySize.putIfAbsent(size, list); | ||
// someone else put a queue in the map before we did | ||
if (prev != null) { | ||
list = prev; | ||
} | ||
} | ||
list.add(new WeakReference<>(buf)); | ||
} | ||
} |