Skip to content

Commit 0d49bd2

Browse files
mukund-thakursteveloughran
authored andcommitted
HADOOP-18105 Implement buffer pooling with weak references (#4263)
part of HADOOP-18103. Required for vectored IO feature. None of current buffer pool implementation is complete. ElasticByteBufferPool doesn't use weak references and could lead to memory leak errors and DirectBufferPool doesn't support caller preferences of direct and heap buffers and has only fixed length buffer implementation. Contributed By: Mukund Thakur
1 parent 1408dd8 commit 0d49bd2

File tree

5 files changed

+491
-2
lines changed

5 files changed

+491
-2
lines changed

hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/ByteBufferPool.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,9 @@ public interface ByteBufferPool {
4545
* @param buffer a direct bytebuffer
4646
*/
4747
void putBuffer(ByteBuffer buffer);
48+
49+
/**
50+
* Clear the buffer pool thus releasing all the buffers.
51+
*/
52+
default void release() { }
4853
}

hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/ElasticByteBufferPool.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636
*/
3737
@InterfaceAudience.Public
3838
@InterfaceStability.Stable
39-
public final class ElasticByteBufferPool implements ByteBufferPool {
40-
private static final class Key implements Comparable<Key> {
39+
public class ElasticByteBufferPool implements ByteBufferPool {
40+
protected static final class Key implements Comparable<Key> {
4141
private final int capacity;
4242
private final long insertionTime;
4343

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
/**
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
package org.apache.hadoop.io;
20+
21+
import java.lang.ref.WeakReference;
22+
import java.nio.ByteBuffer;
23+
import java.util.Map;
24+
import java.util.TreeMap;
25+
26+
import org.apache.hadoop.classification.InterfaceAudience;
27+
import org.apache.hadoop.classification.InterfaceStability;
28+
import org.apache.hadoop.classification.VisibleForTesting;
29+
30+
/**
31+
* Buffer pool implementation which uses weak references to store
32+
* buffers in the pool, such that they are garbage collected when
33+
* there are no references to the buffer during a gc run. This is
34+
* important as direct buffers don't get garbage collected automatically
35+
* during a gc run as they are not stored on heap memory.
36+
* Also the buffers are stored in a tree map which helps in returning
37+
* smallest buffer whose size is just greater than requested length.
38+
* This is a thread safe implementation.
39+
*/
40+
@InterfaceAudience.Private
41+
@InterfaceStability.Unstable
42+
public final class WeakReferencedElasticByteBufferPool extends ElasticByteBufferPool {
43+
44+
/**
45+
* Map to store direct byte buffers of different sizes in the pool.
46+
* Used tree map such that we can return next greater than capacity
47+
* buffer if buffer with exact capacity is unavailable.
48+
* This must be accessed in synchronized blocks.
49+
*/
50+
private final TreeMap<Key, WeakReference<ByteBuffer>> directBuffers =
51+
new TreeMap<>();
52+
53+
/**
54+
* Map to store heap based byte buffers of different sizes in the pool.
55+
* Used tree map such that we can return next greater than capacity
56+
* buffer if buffer with exact capacity is unavailable.
57+
* This must be accessed in synchronized blocks.
58+
*/
59+
private final TreeMap<Key, WeakReference<ByteBuffer>> heapBuffers =
60+
new TreeMap<>();
61+
62+
/**
63+
* Method to get desired buffer tree.
64+
* @param isDirect whether the buffer is heap based or direct.
65+
* @return corresponding buffer tree.
66+
*/
67+
private TreeMap<Key, WeakReference<ByteBuffer>> getBufferTree(boolean isDirect) {
68+
return isDirect
69+
? directBuffers
70+
: heapBuffers;
71+
}
72+
73+
/**
74+
* {@inheritDoc}
75+
*
76+
* @param direct whether we want a direct byte buffer or a heap one.
77+
* @param length length of requested buffer.
78+
* @return returns equal or next greater than capacity buffer from
79+
* pool if already available and not garbage collected else creates
80+
* a new buffer and return it.
81+
*/
82+
@Override
83+
public synchronized ByteBuffer getBuffer(boolean direct, int length) {
84+
TreeMap<Key, WeakReference<ByteBuffer>> buffersTree = getBufferTree(direct);
85+
86+
// Scan the entire tree and remove all weak null references.
87+
buffersTree.entrySet().removeIf(next -> next.getValue().get() == null);
88+
89+
Map.Entry<Key, WeakReference<ByteBuffer>> entry =
90+
buffersTree.ceilingEntry(new Key(length, 0));
91+
// If there is no buffer present in the pool with desired size.
92+
if (entry == null) {
93+
return direct ? ByteBuffer.allocateDirect(length) :
94+
ByteBuffer.allocate(length);
95+
}
96+
// buffer is available in the pool and not garbage collected.
97+
WeakReference<ByteBuffer> bufferInPool = entry.getValue();
98+
buffersTree.remove(entry.getKey());
99+
ByteBuffer buffer = bufferInPool.get();
100+
if (buffer != null) {
101+
return buffer;
102+
}
103+
// buffer was in pool but already got garbage collected.
104+
return direct
105+
? ByteBuffer.allocateDirect(length)
106+
: ByteBuffer.allocate(length);
107+
}
108+
109+
/**
110+
* Return buffer to the pool.
111+
* @param buffer buffer to be returned.
112+
*/
113+
@Override
114+
public synchronized void putBuffer(ByteBuffer buffer) {
115+
buffer.clear();
116+
TreeMap<Key, WeakReference<ByteBuffer>> buffersTree = getBufferTree(buffer.isDirect());
117+
// Buffers are indexed by (capacity, time).
118+
// If our key is not unique on the first try, we try again, since the
119+
// time will be different. Since we use nanoseconds, it's pretty
120+
// unlikely that we'll loop even once, unless the system clock has a
121+
// poor granularity or multi-socket systems have clocks slightly out
122+
// of sync.
123+
while (true) {
124+
Key keyToInsert = new Key(buffer.capacity(), System.nanoTime());
125+
if (!buffersTree.containsKey(keyToInsert)) {
126+
buffersTree.put(keyToInsert, new WeakReference<>(buffer));
127+
return;
128+
}
129+
}
130+
}
131+
132+
/**
133+
* Clear the buffer pool thus releasing all the buffers.
134+
* The caller must remove all references of
135+
* existing buffers before calling this method to avoid
136+
* memory leaks.
137+
*/
138+
@Override
139+
public synchronized void release() {
140+
heapBuffers.clear();
141+
directBuffers.clear();
142+
}
143+
144+
/**
145+
* Get current buffers count in the pool.
146+
* @param isDirect whether we want to count the heap or direct buffers.
147+
* @return count of buffers.
148+
*/
149+
@VisibleForTesting
150+
public synchronized int getCurrentBuffersCount(boolean isDirect) {
151+
return isDirect
152+
? directBuffers.size()
153+
: heapBuffers.size();
154+
}
155+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
package org.apache.hadoop.io;
20+
21+
import java.nio.BufferOverflowException;
22+
import java.nio.ByteBuffer;
23+
24+
import org.assertj.core.api.Assertions;
25+
import org.junit.Test;
26+
27+
import org.apache.hadoop.test.HadoopTestBase;
28+
29+
import static org.apache.hadoop.test.LambdaTestUtils.intercept;
30+
31+
/**
32+
* Non parameterized tests for {@code WeakReferencedElasticByteBufferPool}.
33+
*/
34+
public class TestMoreWeakReferencedElasticByteBufferPool
35+
extends HadoopTestBase {
36+
37+
@Test
38+
public void testMixedBuffersInPool() {
39+
WeakReferencedElasticByteBufferPool pool = new WeakReferencedElasticByteBufferPool();
40+
ByteBuffer buffer1 = pool.getBuffer(true, 5);
41+
ByteBuffer buffer2 = pool.getBuffer(true, 10);
42+
ByteBuffer buffer3 = pool.getBuffer(false, 5);
43+
ByteBuffer buffer4 = pool.getBuffer(false, 10);
44+
ByteBuffer buffer5 = pool.getBuffer(true, 15);
45+
46+
assertBufferCounts(pool, 0, 0);
47+
pool.putBuffer(buffer1);
48+
pool.putBuffer(buffer2);
49+
assertBufferCounts(pool, 2, 0);
50+
pool.putBuffer(buffer3);
51+
assertBufferCounts(pool, 2, 1);
52+
pool.putBuffer(buffer5);
53+
assertBufferCounts(pool, 3, 1);
54+
pool.putBuffer(buffer4);
55+
assertBufferCounts(pool, 3, 2);
56+
pool.release();
57+
assertBufferCounts(pool, 0, 0);
58+
59+
}
60+
61+
@Test
62+
public void testUnexpectedBufferSizes() throws Exception {
63+
WeakReferencedElasticByteBufferPool pool = new WeakReferencedElasticByteBufferPool();
64+
ByteBuffer buffer1 = pool.getBuffer(true, 0);
65+
66+
// try writing a random byte in a 0 length buffer.
67+
// Expected exception as buffer requested is of size 0.
68+
intercept(BufferOverflowException.class,
69+
() -> buffer1.put(new byte[1]));
70+
71+
// Expected IllegalArgumentException as negative length buffer is requested.
72+
intercept(IllegalArgumentException.class,
73+
() -> pool.getBuffer(true, -5));
74+
75+
// test returning null buffer to the pool.
76+
intercept(NullPointerException.class,
77+
() -> pool.putBuffer(null));
78+
}
79+
80+
/**
81+
* Utility method to assert counts of direct and heap buffers in
82+
* the given buffer pool.
83+
* @param pool buffer pool.
84+
* @param numDirectBuffersExpected expected number of direct buffers.
85+
* @param numHeapBuffersExpected expected number of heap buffers.
86+
*/
87+
private void assertBufferCounts(WeakReferencedElasticByteBufferPool pool,
88+
int numDirectBuffersExpected,
89+
int numHeapBuffersExpected) {
90+
Assertions.assertThat(pool.getCurrentBuffersCount(true))
91+
.describedAs("Number of direct buffers in pool")
92+
.isEqualTo(numDirectBuffersExpected);
93+
Assertions.assertThat(pool.getCurrentBuffersCount(false))
94+
.describedAs("Number of heap buffers in pool")
95+
.isEqualTo(numHeapBuffersExpected);
96+
}
97+
}

0 commit comments

Comments
 (0)