2 * Copyright 2017-present Open Networking Foundation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.utils.memory;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 import java.nio.MappedByteBuffer;
23 import java.nio.channels.FileChannel;
28 * This is a special memory descriptor that handles management of {@link MappedByteBuffer} based memory. The
29 * mapped memory descriptor simply points to the memory address of the underlying byte buffer. When memory is reallocated,
30 * the parent {@link MappedMemoryAllocator} is used to create a new {@link MappedByteBuffer}
31 * and free the existing buffer.
33 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
35 public class MappedMemory implements Memory {
36 private static final long MAX_SIZE = Integer.MAX_VALUE - 5;
38 private static final Logger LOGGER = LoggerFactory.getLogger(MappedMemory.class);
41 * Allocates memory mapped to a file on disk.
43 * @param file The file to which to map memory.
44 * @param size The count of the memory to map.
45 * @return The mapped memory.
46 * @throws IllegalArgumentException If {@code count} is greater than {@link MappedMemory#MAX_SIZE}
48 public static MappedMemory allocate(File file, int size) {
49 return new MappedMemoryAllocator(file).allocate(size);
53 * Allocates memory mapped to a file on disk.
55 * @param file The file to which to map memory.
56 * @param mode The mode with which to map memory.
57 * @param size The count of the memory to map.
58 * @return The mapped memory.
59 * @throws IllegalArgumentException If {@code count} is greater than {@link MappedMemory#MAX_SIZE}
61 public static MappedMemory allocate(File file, FileChannel.MapMode mode, int size) {
62 if (size > MAX_SIZE) {
63 throw new IllegalArgumentException("size cannot be greater than " + MAX_SIZE);
65 return new MappedMemoryAllocator(file, mode).allocate(size);
68 private final MappedByteBuffer buffer;
69 private final MappedMemoryAllocator allocator;
70 private final int size;
72 public MappedMemory(MappedByteBuffer buffer, MappedMemoryAllocator allocator) {
74 this.allocator = allocator;
75 this.size = buffer.capacity();
79 * Flushes the mapped buffer to disk.
93 BufferCleaner.freeBuffer(buffer);
94 } catch (Exception e) {
95 if (LOGGER.isDebugEnabled()) {
96 LOGGER.debug("Failed to unmap direct buffer", e);
102 public void close() {