-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathMemoryMappedAllocator.java
More file actions
207 lines (175 loc) · 7.48 KB
/
MemoryMappedAllocator.java
File metadata and controls
207 lines (175 loc) · 7.48 KB
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
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package org.capnproto;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.Cleaner;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class MemoryMappedAllocator implements Allocator {
// cleaner for file cleanup when this is GCed
private static final Cleaner cleaner = Cleaner.create();
private final Cleaner.Cleanable cleanable;
// the length of the random prefix part of the random filename string
private final int PREFIX_LENGTH = 5;
// the used charset for creating random filenames
private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// (minimum) number of bytes in the next allocation
private int nextSize = BuilderArena.SUGGESTED_FIRST_SEGMENT_WORDS;
// the maximum allocateable size
public int maxSegmentBytes = Integer.MAX_VALUE - 2;
// the memory mapped file buffer name prefix
private final String rPrefix;
// the allocation strategy with which the allocation size grows
public AllocationStrategy allocationStrategy =
AllocationStrategy.GROW_HEURISTICALLY;
// hashmaps used for keeping track of files
private final Map<Integer, RandomAccessFile> randomAccFiles = Collections.synchronizedMap(new HashMap<>());
private final Map<Integer, FileChannel> channelMap = Collections.synchronizedMap(new HashMap<>());
public MemoryMappedAllocator(String baseFileName) {
// create random file name with baseFileNamePrefix:
// ${baseFileName}_XXXXX_000001
Random random = new Random();
StringBuilder sb = new StringBuilder(PREFIX_LENGTH);
for (int i = 0; i < PREFIX_LENGTH; i++) {
int index = random.nextInt(CHARSET.length());
sb.append(CHARSET.charAt(index));
}
rPrefix = baseFileName + "_" + sb.toString();
this.cleanable = cleaner.register(this, new State(this.randomAccFiles, rPrefix));
}
public MemoryMappedAllocator(String baseFileName, AllocationStrategy allocationStrategy) {
// create random file name with baseFileNamePrefix:
// ${baseFileName}_XXXXX_000001
Random random = new Random();
StringBuilder sb = new StringBuilder(PREFIX_LENGTH);
for (int i = 0; i < PREFIX_LENGTH; i++) {
int index = random.nextInt(CHARSET.length());
sb.append(CHARSET.charAt(index));
}
rPrefix = baseFileName + "_" + sb.toString();
this.cleanable = cleaner.register(this, new State(this.randomAccFiles, rPrefix));
this.allocationStrategy = allocationStrategy;
}
private static String nameForInt(String prefix, int key) {
String ret = prefix + "_" + String.format("%05d", key);
return ret;
}
private Integer generateFile() throws IOException {
int fCount;
synchronized (randomAccFiles) {
fCount = randomAccFiles.size();
String newFileName = nameForInt(rPrefix, fCount);
RandomAccessFile newFile = new RandomAccessFile(newFileName, "rw");
randomAccFiles.put(fCount, newFile);
File test = new File(newFileName);
test.deleteOnExit();
}
return fCount;
}
/**
* set the grow size of the memory mapped file
*/
@Override
public void setNextAllocationSizeBytes(int nextSize) {
this.nextSize = nextSize;
}
private FileChannel createSegment(int segmentSize) throws IOException {
int fileKey = generateFile();
FileChannel channel = null;
synchronized (channelMap) {
if (!channelMap.containsKey(fileKey)) {
synchronized (randomAccFiles) {
RandomAccessFile file = randomAccFiles.get(fileKey);
file.setLength(segmentSize);
channel = file.getChannel();
channelMap.put(fileKey, channel);
}
}
}
return channel;
}
@Override
public java.nio.ByteBuffer allocateSegment(int minimumSize) {
int size = Math.max(minimumSize, this.nextSize);
MappedByteBuffer result = null;
try {
FileChannel channel = createSegment(size);
result = channel.map(FileChannel.MapMode.READ_WRITE, 0, size);
}
catch (IOException e)
{
System.err.println("IOException: allocateSegment failed with:" + e);
}
switch (this.allocationStrategy) {
case GROW_HEURISTICALLY:
if (size < this.maxSegmentBytes - this.nextSize) {
this.nextSize += size;
} else {
this.nextSize = maxSegmentBytes;
}
break;
case FIXED_SIZE:
break;
}
// if (size < this.maxSegmentBytes - this.nextSize) {
// this.nextSize += size;
// } else {
// this.nextSize = maxSegmentBytes;
// }
return result;
}
private static class State implements Runnable {
private final Map<Integer, RandomAccessFile> randomAccFiles;
private final String rPrefix;
State(Map<Integer, RandomAccessFile> files, String rPrefix) {
this.randomAccFiles = files;
this.rPrefix = rPrefix;
}
@Override
public void run() {
// Cleanup logic: delete all files
for (Map.Entry<Integer,RandomAccessFile> entry : randomAccFiles.entrySet()) {
try {
entry.getValue().close();
}
catch (IOException e)
{
}
String name = nameForInt(rPrefix, entry.getKey());
File file = new File(name);
file.delete();
}
}
}
/**
* Explicit cleanup: WARNING: this invalidates all alloceted buffers,
* use close() after using the ByteBuffers.
*/
public void close() {
cleanable.clean();
}
}