-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
DataOutputBuffer.java
304 lines (262 loc) · 8.38 KB
/
DataOutputBuffer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.io.util;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.cassandra.utils.ByteBufferUtil;
import static org.apache.cassandra.config.CassandraRelevantProperties.DATA_OUTPUT_BUFFER_ALLOCATE_TYPE;
import static org.apache.cassandra.config.CassandraRelevantProperties.DOB_DOUBLING_THRESHOLD_MB;
import static org.apache.cassandra.config.CassandraRelevantProperties.DOB_MAX_RECYCLE_BYTES;
/**
* An implementation of the DataOutputStream interface using a FastByteArrayOutputStream and exposing
* its buffer so copies can be avoided.
*
* This class is completely thread unsafe.
*/
public class DataOutputBuffer extends BufferedDataOutputStreamPlus
{
/*
* Threshold at which resizing transitions from doubling to increasing by 50%
*/
static final long DOUBLING_THRESHOLD = DOB_DOUBLING_THRESHOLD_MB.getLong();
/*
* Only recycle OutputBuffers up to 1Mb. Larger buffers will be trimmed back to this size.
*/
private static final int MAX_RECYCLE_BUFFER_SIZE = DOB_MAX_RECYCLE_BYTES.getInt();
private enum AllocationType { DIRECT, ONHEAP }
private static final AllocationType ALLOCATION_TYPE = DATA_OUTPUT_BUFFER_ALLOCATE_TYPE.getEnum(AllocationType.DIRECT);
private static final int DEFAULT_INITIAL_BUFFER_SIZE = 128;
/**
* Scratch buffers used mostly for serializing in memory. It's important to call #close() when finished
* to keep the memory overhead from being too large in the system.
*/
public static final FastThreadLocal<DataOutputBuffer> scratchBuffer = new FastThreadLocal<DataOutputBuffer>()
{
@Override
protected DataOutputBuffer initialValue()
{
return new DataOutputBuffer()
{
@Override
public void close()
{
if (buffer != null && buffer.capacity() <= MAX_RECYCLE_BUFFER_SIZE)
{
buffer.clear();
}
else
{
setBuffer(allocate(DEFAULT_INITIAL_BUFFER_SIZE));
}
}
@Override
protected ByteBuffer allocate(int size)
{
return ALLOCATION_TYPE == AllocationType.DIRECT ?
ByteBuffer.allocateDirect(size) :
ByteBuffer.allocate(size);
}
};
}
};
public DataOutputBuffer()
{
super(DEFAULT_INITIAL_BUFFER_SIZE);
}
public DataOutputBuffer(int size)
{
super(size);
}
public DataOutputBuffer(ByteBuffer buffer)
{
super(buffer);
}
@Override
public void flush()
{
}
//The actual value observed in Hotspot is only -2
//ByteArrayOutputStream uses -8
@VisibleForTesting
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
@VisibleForTesting
static int saturatedArraySizeCast(long size)
{
Preconditions.checkArgument(size >= 0);
return (int)Math.min(MAX_ARRAY_SIZE, size);
}
@VisibleForTesting
static int checkedArraySizeCast(long size)
{
Preconditions.checkArgument(size >= 0);
Preconditions.checkArgument(size <= MAX_ARRAY_SIZE);
return (int)size;
}
@Override
protected void doFlush(int count) throws IOException
{
expandToFit(count);
}
//Hack for test, make it possible to override checking the buffer capacity
@VisibleForTesting
long capacity()
{
return buffer.capacity();
}
@VisibleForTesting
long validateReallocation(long newSize)
{
int saturatedSize = saturatedArraySizeCast(newSize);
if (saturatedSize <= capacity())
throw new BufferOverflowException();
return saturatedSize;
}
@VisibleForTesting
long calculateNewSize(long count)
{
long capacity = capacity();
//Both sides of this max expression need to use long arithmetic to avoid integer overflow
//count and capacity are longs so that ensures it right now.
long newSize = capacity + count;
//For large buffers don't double, increase by 50%
if (capacity > 1024L * 1024L * DOUBLING_THRESHOLD)
newSize = Math.max((capacity * 3L) / 2L, newSize);
else
newSize = Math.max(capacity * 2L, newSize);
return validateReallocation(newSize);
}
protected void expandToFit(long count)
{
if (count <= 0)
return;
ByteBuffer newBuffer = allocate(checkedArraySizeCast(calculateNewSize(count)));
buffer.flip();
newBuffer.put(buffer);
setBuffer(newBuffer);
}
protected void setBuffer(ByteBuffer newBuffer)
{
FileUtils.clean(buffer); // free if direct
buffer = newBuffer;
}
@Override
protected WritableByteChannel newDefaultChannel()
{
return new GrowingChannel();
}
public void clear()
{
buffer.clear();
}
@VisibleForTesting
final class GrowingChannel implements WritableByteChannel
{
public int write(ByteBuffer src)
{
int count = src.remaining();
expandToFit(count);
buffer.put(src);
return count;
}
public boolean isOpen()
{
return true;
}
public void close()
{
}
}
@Override
public void close()
{
}
public ByteBuffer buffer()
{
return buffer(true);
}
public ByteBuffer buffer(boolean duplicate)
{
if (!duplicate)
{
ByteBuffer buf = buffer;
buf.flip();
buffer = null;
return buf;
}
ByteBuffer result = buffer.duplicate();
result.flip();
return result;
}
/**
* Gets the underlying ByteBuffer and calls {@link ByteBuffer#flip()}. This method is "unsafe" in the sense that
* it returns the underlying buffer, which may be modified by other methods after calling this method (or cleared on
* {@link #close()}). If the calling logic knows that no new calls to this object will happen after calling this
* method, then this method can avoid the copying done in {@link #asNewBuffer()}, and {@link #buffer()}.
*/
public ByteBuffer unsafeGetBufferAndFlip()
{
buffer.flip();
return buffer;
}
public byte[] getData()
{
assert buffer.arrayOffset() == 0;
return buffer.array();
}
public int getLength()
{
return buffer.position();
}
public boolean hasPosition()
{
return true;
}
public long position()
{
return getLength();
}
public ByteBuffer asNewBuffer()
{
return ByteBuffer.wrap(toByteArray());
}
public byte[] toByteArray()
{
ByteBuffer buffer = buffer();
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
return result;
}
public String asString()
{
try
{
return ByteBufferUtil.string(buffer(), StandardCharsets.UTF_8);
}
catch (CharacterCodingException e)
{
throw new RuntimeException(e);
}
}
}