You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datasketches.apache.org by le...@apache.org on 2020/12/05 02:24:07 UTC
[incubator-datasketches-memory] branch JKD11Compatibility updated:
Removed memory-mapped file functionality.
This is an automated email from the ASF dual-hosted git repository.
leerho pushed a commit to branch JKD11Compatibility
in repository https://gitbox.apache.org/repos/asf/incubator-datasketches-memory.git
The following commit(s) were added to refs/heads/JKD11Compatibility by this push:
new 23ebe51 Removed memory-mapped file functionality.
23ebe51 is described below
commit 23ebe51d9aa0efafdb04b2ce0ee76f179bcf8db7
Author: Lee Rhodes <le...@users.noreply.github.com>
AuthorDate: Fri Dec 4 18:23:50 2020 -0800
Removed memory-mapped file functionality.
Updated code to use JDK9+ compatible Cleaner, which is incompatible with
the use of the JDK8 internal Cleaner.
Removed the off-heap memory tracking that was provided by NIO/Bits class
in JDK8. This is no longer available.
Removed some UTF8 tests that leveraged ProtoBuf, because of problems
with JDK11 compatibility of Protobuf.
Updated the documentation in the package-info class.
---
.../apache/datasketches/memory/AllocateDirect.java | 40 +--
.../datasketches/memory/AllocateDirectMap.java | 318 ---------------------
.../memory/AllocateDirectWritableMap.java | 57 ----
.../memory/BaseWritableMemoryImpl.java | 43 ++-
.../java/org/apache/datasketches/memory/Map.java | 46 ---
.../org/apache/datasketches/memory/MapHandle.java | 64 -----
.../org/apache/datasketches/memory/Memory.java | 47 +--
.../org/apache/datasketches/memory/NioBits.java | 175 ------------
.../org/apache/datasketches/memory/UnsafeUtil.java | 26 +-
.../apache/datasketches/memory/WritableMap.java | 37 ---
.../datasketches/memory/WritableMapHandle.java | 46 ---
.../apache/datasketches/memory/WritableMemory.java | 84 +++---
.../apache/datasketches/memory/package-info.java | 33 +--
.../memory/AllocateDirectMapMemoryTest.java | 168 -----------
.../AllocateDirectWritableMapMemoryTest.java | 248 ----------------
.../apache/datasketches/memory/LeafImplTest.java | 81 ------
.../memory/MemoryReadWriteSafetyTest.java | 37 ---
.../org/apache/datasketches/memory/MemoryTest.java | 24 --
.../apache/datasketches/memory/NioBitsTest.java | 79 -----
.../datasketches/memory/SpecificLeafTest.java | 43 ---
.../apache/datasketches/memory/UnsafeUtilTest.java | 6 +
.../org/apache/datasketches/memory/Utf8Test.java | 14 +-
22 files changed, 114 insertions(+), 1602 deletions(-)
diff --git a/src/main/java/org/apache/datasketches/memory/AllocateDirect.java b/src/main/java/org/apache/datasketches/memory/AllocateDirect.java
index 423c074..5d90a4d 100644
--- a/src/main/java/org/apache/datasketches/memory/AllocateDirect.java
+++ b/src/main/java/org/apache/datasketches/memory/AllocateDirect.java
@@ -21,12 +21,12 @@ package org.apache.datasketches.memory;
import static org.apache.datasketches.memory.UnsafeUtil.unsafe;
+//import sun.misc.Cleaner; //JDK 8
+import java.lang.ref.Cleaner; //JDK 9+
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import sun.misc.Cleaner; //JDK 8
-//import jdk.internal.ref.Cleaner; //JDK 9+
-
/**
* Provides access to direct (native) memory.
*
@@ -35,9 +35,9 @@ import sun.misc.Cleaner; //JDK 8
*/
final class AllocateDirect implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AllocateDirect.class);
-
+ private static final Cleaner cleaner = UnsafeUtil.cleaner;
private final Deallocator deallocator;
- private final Cleaner cleaner;
+ private final Cleaner.Cleanable cleanable;
private final long nativeBaseOffset;
/**
@@ -49,26 +49,15 @@ final class AllocateDirect implements AutoCloseable {
* @param capacityBytes the the requested capacity of off-heap memory. Cannot be zero.
*/
AllocateDirect(final long capacityBytes) {
- final boolean pageAligned = NioBits.isPageAligned();
- final long pageSize = NioBits.pageSize();
- final long allocationSize = capacityBytes + (pageAligned ? pageSize : 0);
- NioBits.reserveMemory(allocationSize, capacityBytes);
-
final long nativeAddress;
try {
- nativeAddress = unsafe.allocateMemory(allocationSize);
+ nativeAddress = unsafe.allocateMemory(capacityBytes);
} catch (final OutOfMemoryError err) {
- NioBits.unreserveMemory(allocationSize, capacityBytes);
throw err;
}
- if (pageAligned && nativeAddress % pageSize != 0) {
- //Round up to page boundary
- nativeBaseOffset = (nativeAddress & ~(pageSize - 1L)) + pageSize;
- } else {
- nativeBaseOffset = nativeAddress;
- }
- deallocator = new Deallocator(nativeAddress, allocationSize, capacityBytes);
- cleaner = Cleaner.create(this, deallocator);
+ nativeBaseOffset = nativeAddress;
+ deallocator = new Deallocator(nativeAddress, capacityBytes);
+ cleanable = cleaner.register(this, deallocator);
}
@Override
@@ -82,7 +71,7 @@ final class AllocateDirect implements AutoCloseable {
// This Cleaner.clean() call effectively just removes the Cleaner from the internal linked
// list of all cleaners. It will delegate to Deallocator.deallocate() which will be a no-op
// because the valid state is already changed.
- cleaner.clean();
+ cleanable.clean();
return true;
} else {
return false;
@@ -90,7 +79,7 @@ final class AllocateDirect implements AutoCloseable {
} finally {
BaseState.reachabilityFence(this);
}
- }
+ } //end of doClose()
long getNativeBaseOffset() {
return nativeBaseOffset;
@@ -103,15 +92,13 @@ final class AllocateDirect implements AutoCloseable {
private static final class Deallocator implements Runnable {
//This is the only place the actual native address is kept for use by unsafe.freeMemory();
private final long nativeAddress;
- private final long allocationSize;
private final long capacity;
private final StepBoolean valid = new StepBoolean(true); //only place for this
- private Deallocator(final long nativeAddress, final long allocationSize, final long capacity) {
+ private Deallocator(final long nativeAddress, final long capacity) {
BaseState.currentDirectMemoryAllocations_.incrementAndGet();
BaseState.currentDirectMemoryAllocated_.addAndGet(capacity);
this.nativeAddress = nativeAddress;
- this.allocationSize = allocationSize;
this.capacity = capacity;
assert nativeAddress != 0;
}
@@ -125,14 +112,13 @@ final class AllocateDirect implements AutoCloseable {
deallocate(true);
}
- boolean deallocate(final boolean calledFromCleaner) {
+ private boolean deallocate(final boolean calledFromCleaner) {
if (valid.change()) {
if (calledFromCleaner) {
// Warn about non-deterministic resource cleanup.
LOG.warn("A WritableDirectHandle was not closed manually");
}
unsafe.freeMemory(nativeAddress);
- NioBits.unreserveMemory(allocationSize, capacity);
BaseState.currentDirectMemoryAllocations_.decrementAndGet();
BaseState.currentDirectMemoryAllocated_.addAndGet(-capacity);
return true;
diff --git a/src/main/java/org/apache/datasketches/memory/AllocateDirectMap.java b/src/main/java/org/apache/datasketches/memory/AllocateDirectMap.java
deleted file mode 100644
index a7f6d8c..0000000
--- a/src/main/java/org/apache/datasketches/memory/AllocateDirectMap.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-import static org.apache.datasketches.memory.UnsafeUtil.unsafe;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.nio.MappedByteBuffer;
-import java.nio.channels.FileChannel;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import sun.misc.Cleaner; //JDK 8
-//import jdk.internal.ref.Cleaner; //JDK 9+
-import sun.nio.ch.FileChannelImpl;
-
-/**
- * Allocates direct memory used to memory map files for read operations.
- * (including those > 2GB).
- *
- * <p>To understand how it works, reference native code for map0, unmap0:
- * <a href="http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/f940e7a48b72/src/solaris/native/
- * sun/nio/ch/FileChannelImpl.c">
- * FileChannelImpl.c</a></p>
- *
- * <p>To understand how it works, reference native code for load0(), isLoaded0(), and force0():
- * <a href="http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/f940e7a48b72/src/solaris/native/
- * java/nio/MappedByteBuffer.c">
- * MappedByteBuffer.c</a></p>
- *
- * @author Roman Leventov
- * @author Lee Rhodes
- * @author Praveenkumar Venkatesan
- */
-class AllocateDirectMap implements Map {
- private static final Logger LOG = LoggerFactory.getLogger(AllocateDirectMap.class);
-
- private static final int MAP_RO = 0;
- private static final int MAP_RW = 1;
-
- private static final Method FILE_CHANNEL_IMPL_MAP0_METHOD;
- private static final Method FILE_CHANNEL_IMPL_UNMAP0_METHOD;
-
- private static final Method MAPPED_BYTE_BUFFER_LOAD0_METHOD;
- private static final Method MAPPED_BYTE_BUFFER_ISLOADED0_METHOD;
- static final Method MAPPED_BYTE_BUFFER_FORCE0_METHOD;
-
- static {
- try {
- FILE_CHANNEL_IMPL_MAP0_METHOD = FileChannelImpl.class
- .getDeclaredMethod("map0", int.class, long.class, long.class);
- FILE_CHANNEL_IMPL_MAP0_METHOD.setAccessible(true);
-
- FILE_CHANNEL_IMPL_UNMAP0_METHOD = FileChannelImpl.class
- .getDeclaredMethod("unmap0", long.class, long.class);
- FILE_CHANNEL_IMPL_UNMAP0_METHOD.setAccessible(true);
-
- MAPPED_BYTE_BUFFER_LOAD0_METHOD = MappedByteBuffer.class
- .getDeclaredMethod("load0", long.class, long.class);
- MAPPED_BYTE_BUFFER_LOAD0_METHOD.setAccessible(true);
-
- MAPPED_BYTE_BUFFER_ISLOADED0_METHOD = MappedByteBuffer.class
- .getDeclaredMethod("isLoaded0", long.class, long.class, int.class);
- MAPPED_BYTE_BUFFER_ISLOADED0_METHOD.setAccessible(true);
-
- MAPPED_BYTE_BUFFER_FORCE0_METHOD = MappedByteBuffer.class
- .getDeclaredMethod("force0", FileDescriptor.class, long.class, long.class);
- MAPPED_BYTE_BUFFER_FORCE0_METHOD.setAccessible(true);
- } catch (final Exception e) {
- throw new RuntimeException("Could not reflect static methods: " + e);
- }
- }
-
- private final Deallocator deallocator;
- private final Cleaner cleaner;
-
- final long capacityBytes;
- final RandomAccessFile raf;
- final long nativeBaseOffset;
- final boolean resourceReadOnly;
-
- //called from AllocateDirectWritableMap constructor
- @SuppressWarnings("resource")
- AllocateDirectMap(final File file, final long fileOffsetBytes, final long capacityBytes,
- final boolean localReadOnly) {
- this.capacityBytes = capacityBytes;
- resourceReadOnly = isFileReadOnly(file);
- final long fileLength = file.length();
- if ((localReadOnly || resourceReadOnly) && fileOffsetBytes + capacityBytes > fileLength) {
- throw new IllegalArgumentException(
- "Read-only mode and requested map length is greater than current file length: "
- + "Requested Length = " + (fileOffsetBytes + capacityBytes)
- + ", Current File Length = " + fileLength);
- }
- raf = mapper(file, fileOffsetBytes, capacityBytes, resourceReadOnly);
- nativeBaseOffset = map(raf.getChannel(), resourceReadOnly, fileOffsetBytes, capacityBytes);
- deallocator = new Deallocator(nativeBaseOffset, capacityBytes, raf);
- cleaner = Cleaner.create(this, deallocator);
- }
-
- @Override
- public void load() {
- madvise();
- // Performance optimization. Read a byte from each page to bring it into memory.
- final int ps = NioBits.pageSize();
- final int count = NioBits.pageCount(capacityBytes);
- long offset = nativeBaseOffset;
- for (int i = 0; i < count; i++) {
- unsafe.getByte(offset);
- offset += ps;
- }
- }
-
- @Override
- public boolean isLoaded() {
- try {
- final int pageCount = NioBits.pageCount(capacityBytes);
- return (boolean) MAPPED_BYTE_BUFFER_ISLOADED0_METHOD
- //isLoaded0 is effectively static, so ZERO_READ_ONLY_DIRECT_BYTE_BUFFER is not modified
- .invoke(AccessByteBuffer.ZERO_READ_ONLY_DIRECT_BYTE_BUFFER,
- nativeBaseOffset,
- capacityBytes,
- pageCount);
- } catch (final Exception e) {
- throw new RuntimeException(
- String.format("Encountered %s exception while loading", e.getClass()));
- }
- }
-
- @Override
- public void close() {
- doClose();
- }
-
- boolean doClose() {
- try {
- if (deallocator.deallocate(false)) {
- // This Cleaner.clean() call effectively just removes the Cleaner from the internal linked
- // list of all cleaners. It will delegate to Deallocator.deallocate() which will be a no-op
- // because the valid state is already changed.
- cleaner.clean();
- return true;
- } else {
- return false;
- }
- } finally {
- BaseState.reachabilityFence(this);
- }
- }
-
- StepBoolean getValid() {
- return deallocator.getValid();
- }
-
- // Private methods
- /**
- * called by load(). Calls the native method load0 in MappedByteBuffer.java, implemented
- * in MappedByteBuffer.c. See reference at top of class. load0 allows setting a mapping length
- * of greater than 2GB.
- */
- private void madvise() {
- try {
- MAPPED_BYTE_BUFFER_LOAD0_METHOD
- //load0 is effectively static, so ZERO_READ_ONLY_DIRECT_BYTE_BUFFER is not modified
- .invoke(AccessByteBuffer.ZERO_READ_ONLY_DIRECT_BYTE_BUFFER,
- nativeBaseOffset,
- capacityBytes);
- } catch (final Exception e) {
- throw new RuntimeException(
- String.format("Encountered %s exception while loading", e.getClass()));
- }
- }
-
- //Does the actual mapping work, resourceReadOnly must already be set
- private static RandomAccessFile mapper(final File file, final long fileOffset,
- final long capacityBytes, final boolean resourceReadOnly) {
-
- final String mode = resourceReadOnly ? "r" : "rw";
- final RandomAccessFile raf;
- try {
- raf = new RandomAccessFile(file, mode);
- if (fileOffset + capacityBytes > raf.length()) {
- raf.setLength(fileOffset + capacityBytes);
- }
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
- return raf;
- }
-
- /**
- * Creates a mapping of the FileChannel starting at position and of size length to pages
- * in the OS. This may throw OutOfMemory error if you have exhausted memory.
- * You can try to force garbage collection and re-attempt.
- *
- * <p>map0 is a native method of FileChannelImpl.java implemented in FileChannelImpl.c.
- * See reference at top of class.</p>
- *
- * @param fileChannel the FileChannel
- * @param position the offset in bytes into the FileChannel
- * @param lengthBytes the length in bytes
- * @return the native base offset address
- * @throws RuntimeException Encountered an exception while mapping
- */
- private static long map(final FileChannel fileChannel, final boolean resourceReadOnly,
- final long position, final long lengthBytes) {
- final int pagePosition = (int) (position % unsafe.pageSize());
- final long mapPosition = position - pagePosition;
- final long mapSize = lengthBytes + pagePosition;
- final int mapMode = resourceReadOnly ? MAP_RO : MAP_RW;
- try {
- final long nativeBaseOffset =
- (long) FILE_CHANNEL_IMPL_MAP0_METHOD.invoke(fileChannel, mapMode, mapPosition, mapSize);
- return nativeBaseOffset;
- } catch (final InvocationTargetException e) {
- throw new RuntimeException("Exception while mapping", e.getTargetException());
- } catch (final IllegalAccessException e) {
- throw new RuntimeException("Exception while mapping", e);
- }
- }
-
- static boolean isFileReadOnly(final File file) {
- try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
- raf.close();
- return false;
- } catch (final SecurityException | IOException f) { //could not open for write
- return true;
- }
- }
-
- private static final class Deallocator implements Runnable {
- private final RandomAccessFile myRaf;
- private final FileChannel myFc;
- //This is the only place the actual native offset is kept for use by unsafe.freeMemory();
- private final long actualNativeBaseOffset;
- private final long myCapacity;
- private final StepBoolean valid = new StepBoolean(true); //only place for this
-
- Deallocator(final long nativeBaseOffset, final long capacityBytes,
- final RandomAccessFile raf) {
- BaseState.currentDirectMemoryMapAllocations_.incrementAndGet();
- BaseState.currentDirectMemoryMapAllocated_.addAndGet(capacityBytes);
- myRaf = raf;
- assert myRaf != null;
- myFc = myRaf.getChannel();
- actualNativeBaseOffset = nativeBaseOffset;
- assert actualNativeBaseOffset != 0;
- myCapacity = capacityBytes;
- assert myCapacity != 0;
- }
-
- StepBoolean getValid() {
- return valid;
- }
-
- @Override
- public void run() {
- deallocate(true);
- }
-
- boolean deallocate(final boolean calledFromCleaner) {
- if (valid.change()) {
- if (calledFromCleaner) {
- // Warn about non-deterministic resource cleanup.
- LOG.warn("A WritableMapHandle was not closed manually");
- }
- try {
- unmap();
- }
- finally {
- BaseState.currentDirectMemoryMapAllocations_.decrementAndGet();
- BaseState.currentDirectMemoryMapAllocated_.addAndGet(-myCapacity);
- }
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Removes existing mapping. <i>unmap0</i> is a native method in FileChannelImpl.c. See
- * reference at top of class.
- */
- private void unmap() throws RuntimeException {
- try {
- FILE_CHANNEL_IMPL_UNMAP0_METHOD.invoke(myFc, actualNativeBaseOffset, myCapacity);
- myRaf.close();
- } catch (final Exception e) {
- throw new RuntimeException(
- String.format("Encountered %s exception while freeing memory", e.getClass()));
- }
- }
- } //End of class Deallocator
-
-}
diff --git a/src/main/java/org/apache/datasketches/memory/AllocateDirectWritableMap.java b/src/main/java/org/apache/datasketches/memory/AllocateDirectWritableMap.java
deleted file mode 100644
index d0b1046..0000000
--- a/src/main/java/org/apache/datasketches/memory/AllocateDirectWritableMap.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-import java.io.File;
-
-/**
- * Allocates direct memory used to memory map files for write operations
- * (including those > 2GB).
- *
- * @author Lee Rhodes
- * @author Roman Leventov
- * @author Praveenkumar Venkatesan
- */
-//Called from WritableMemory, implements combo of WritableMemory with WritableMap resource
-final class AllocateDirectWritableMap extends AllocateDirectMap implements WritableMap {
-
- AllocateDirectWritableMap(final File file, final long fileOffsetBytes,
- final long capacityBytes, final boolean localReadOnly) {
- super(file, fileOffsetBytes, capacityBytes, localReadOnly);
- }
-
- @Override
- public void force() {
- if (resourceReadOnly) {
- throw new ReadOnlyException("Memory Mapped File is Read Only.");
- }
- try {
- MAPPED_BYTE_BUFFER_FORCE0_METHOD
- //force0 is effectively static, so ZERO_READ_ONLY_DIRECT_BYTE_BUFFER is not modified
- .invoke(AccessByteBuffer.ZERO_READ_ONLY_DIRECT_BYTE_BUFFER,
- raf.getFD(),
- nativeBaseOffset,
- capacityBytes);
- } catch (final Exception e) {
- throw new RuntimeException(String.format("Encountered %s exception in force. "
- + e.getClass()));
- }
- }
-}
diff --git a/src/main/java/org/apache/datasketches/memory/BaseWritableMemoryImpl.java b/src/main/java/org/apache/datasketches/memory/BaseWritableMemoryImpl.java
index c0809a3..af89ab1 100644
--- a/src/main/java/org/apache/datasketches/memory/BaseWritableMemoryImpl.java
+++ b/src/main/java/org/apache/datasketches/memory/BaseWritableMemoryImpl.java
@@ -30,7 +30,6 @@ import static org.apache.datasketches.memory.UnsafeUtil.ARRAY_SHORT_INDEX_SCALE;
import static org.apache.datasketches.memory.UnsafeUtil.checkBounds;
import static org.apache.datasketches.memory.UnsafeUtil.unsafe;
-import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -83,7 +82,7 @@ abstract class BaseWritableMemoryImpl extends WritableMemory {
if (abb.resourceReadOnly && !localReadOnly) {
throw new ReadOnlyException("ByteBuffer is Read Only");
}
- final int typeId = (abb.resourceReadOnly || localReadOnly) ? READONLY : 0;
+ final int typeId = abb.resourceReadOnly || localReadOnly ? READONLY : 0;
return isNativeByteOrder(byteOrder)
? new BBWritableMemoryImpl(abb.unsafeObj, abb.nativeBaseOffset,
abb.regionOffset, abb.capacityBytes, typeId, byteBuf)
@@ -91,24 +90,24 @@ abstract class BaseWritableMemoryImpl extends WritableMemory {
abb.regionOffset, abb.capacityBytes, typeId, byteBuf);
}
- @SuppressWarnings("resource")
- static WritableMapHandle wrapMap(final File file, final long fileOffsetBytes,
- final long capacityBytes, final boolean localReadOnly, final ByteOrder byteOrder) {
-
- final AllocateDirectWritableMap dirWMap =
- new AllocateDirectWritableMap(file, fileOffsetBytes, capacityBytes, localReadOnly);
- if (dirWMap.resourceReadOnly && !localReadOnly) {
- dirWMap.close();
- throw new ReadOnlyException("File is Read Only");
- }
- final int typeId = (dirWMap.resourceReadOnly || localReadOnly) ? READONLY : 0;
- final BaseWritableMemoryImpl wmem = isNativeByteOrder(byteOrder)
- ? new MapWritableMemoryImpl(dirWMap.nativeBaseOffset, 0L, capacityBytes,
- typeId, dirWMap.getValid())
- : new MapNonNativeWritableMemoryImpl(dirWMap.nativeBaseOffset, 0L, capacityBytes,
- typeId, dirWMap.getValid());
- return new WritableMapHandle(dirWMap, wmem);
- }
+ // @SuppressWarnings("resource")
+ // static WritableMapHandle wrapMap(final File file, final long fileOffsetBytes,
+ // final long capacityBytes, final boolean localReadOnly, final ByteOrder byteOrder) {
+ //
+ // final AllocateDirectWritableMap dirWMap =
+ // new AllocateDirectWritableMap(file, fileOffsetBytes, capacityBytes, localReadOnly);
+ // if (dirWMap.resourceReadOnly && !localReadOnly) {
+ // dirWMap.close();
+ // throw new ReadOnlyException("File is Read Only");
+ // }
+ // final int typeId = (dirWMap.resourceReadOnly || localReadOnly) ? READONLY : 0;
+ // final BaseWritableMemoryImpl wmem = isNativeByteOrder(byteOrder)
+ // ? new MapWritableMemoryImpl(dirWMap.nativeBaseOffset, 0L, capacityBytes,
+ // typeId, dirWMap.getValid())
+ // : new MapNonNativeWritableMemoryImpl(dirWMap.nativeBaseOffset, 0L, capacityBytes,
+ // typeId, dirWMap.getValid());
+ // return new WritableMapHandle(dirWMap, wmem);
+ // }
@SuppressWarnings("resource")
static WritableDirectHandle wrapDirect(final long capacityBytes,
@@ -459,7 +458,7 @@ abstract class BaseWritableMemoryImpl extends WritableMemory {
private void writeByteArrayTo(final byte[] unsafeObj, final long offsetBytes,
final long lengthBytes, final WritableByteChannel out) throws IOException {
final int off =
- Ints.checkedCast((getCumulativeOffset(offsetBytes)) - UnsafeUtil.ARRAY_BYTE_BASE_OFFSET);
+ Ints.checkedCast(getCumulativeOffset(offsetBytes) - UnsafeUtil.ARRAY_BYTE_BASE_OFFSET);
final int len = Ints.checkedCast(lengthBytes);
final ByteBuffer bufToWrite = ByteBuffer.wrap(unsafeObj, off, len);
writeFully(bufToWrite, out);
@@ -483,7 +482,7 @@ abstract class BaseWritableMemoryImpl extends WritableMemory {
private void writeToWithExtraCopy(long offsetBytes, long lengthBytes,
final WritableByteChannel out) throws IOException {
// Keep the bufLen a multiple of 8, to maybe allow getByteArray() to go a faster path.
- final int bufLen = Ints.checkedCast(Math.max(8, Math.min((getCapacity() / 1024) & ~7L, 4096)));
+ final int bufLen = Ints.checkedCast(Math.max(8, Math.min(getCapacity() / 1024 & ~7L, 4096)));
final byte[] buf = new byte[bufLen];
final ByteBuffer bufToWrite = ByteBuffer.wrap(buf);
while (lengthBytes > 0) {
diff --git a/src/main/java/org/apache/datasketches/memory/Map.java b/src/main/java/org/apache/datasketches/memory/Map.java
deleted file mode 100644
index 339ed07..0000000
--- a/src/main/java/org/apache/datasketches/memory/Map.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-/**
- * Read only interface for a memory mapped file
- *
- * @author Roman Leventov
- * @author Lee Rhodes
- * @author Praveenkumar Venkatesan
- */
-interface Map extends AutoCloseable {
-
- /**
- * @see <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html#load--">
- * java/nio/MappedByteBuffer.load</a>
- */
- void load();
-
- /**
- * @return true if loaded
- *
- * @see <a href=
- * "https://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html#isLoaded--"> java
- * /nio/MappedByteBuffer.isLoaded</a>
- */
- boolean isLoaded();
-
-}
diff --git a/src/main/java/org/apache/datasketches/memory/MapHandle.java b/src/main/java/org/apache/datasketches/memory/MapHandle.java
deleted file mode 100644
index 181c818..0000000
--- a/src/main/java/org/apache/datasketches/memory/MapHandle.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-/**
- * A Handle for a memory-mapped, read-only file resource.
- * Please read Javadocs for {@link Handle}.
- *
- * @author Lee Rhodes
- * @author Roman Leventov
- */
-//Joins a Read-only Handle with an AutoCloseable Map resource.
-public class MapHandle implements Map, Handle {
- /**
- * Having at least one final field makes this class safe for concurrent publication.
- */
- final AllocateDirectMap dirMap;
- private BaseWritableMemoryImpl wMem;
-
- MapHandle(final AllocateDirectMap dirMap, final BaseWritableMemoryImpl wMem) {
- this.dirMap = dirMap;
- this.wMem = wMem;
- }
-
- @Override
- public Memory get() {
- return wMem;
- }
-
- @Override
- public void close() {
- if (dirMap.doClose()) {
- wMem = null;
- }
- }
-
- @Override
- public void load() {
- dirMap.load();
- }
-
- @Override
- public boolean isLoaded() {
- return dirMap.isLoaded();
- }
-
-}
diff --git a/src/main/java/org/apache/datasketches/memory/Memory.java b/src/main/java/org/apache/datasketches/memory/Memory.java
index 3af3631..07b0342 100644
--- a/src/main/java/org/apache/datasketches/memory/Memory.java
+++ b/src/main/java/org/apache/datasketches/memory/Memory.java
@@ -19,11 +19,6 @@
package org.apache.datasketches.memory;
-import static org.apache.datasketches.memory.Util.negativeCheck;
-import static org.apache.datasketches.memory.Util.nullCheck;
-import static org.apache.datasketches.memory.Util.zeroCheck;
-
-import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -79,46 +74,6 @@ public abstract class Memory extends BaseState {
return BaseWritableMemoryImpl.wrapByteBuffer(byteBuf, true, byteOrder);
}
- //MAP
- /**
- * Maps the entire given file into native-ordered Memory for read operations
- * (including those > 2GB).
- * Calling this method is equivalent to calling {@link #map(File, long, long, ByteOrder)
- * map(file, 0, file.length(), ByteOrder.nativeOrder())}.
- *
- * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
- * <i>Memory.map(...)</i>.
- * @param file the given file to map
- * @return <i>MapHandle</i> for managing the mapped Memory.
- * Please read Javadocs for {@link Handle}.
- * @throws IOException if file not found or a RuntimeException.
- */
- public static MapHandle map(final File file) throws IOException {
- return map(file, 0, file.length(), ByteOrder.nativeOrder());
- }
-
- /**
- * Maps the specified portion of the given file into Memory for read operations
- * (including those > 2GB).
- *
- * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
- * <i>Memory.map(...)</i>.
- * @param file the given file to map. It may not be null.
- * @param fileOffsetBytes the position in the given file in bytes. It may not be negative.
- * @param capacityBytes the size of the mapped Memory. It may not be negative or zero.
- * @param byteOrder the byte order to be used for the mapped Memory. It may not be null.
- * @return <i>MapHandle</i> for managing the mapped Memory.
- * Please read Javadocs for {@link Handle}.
- * @throws IOException if file not found or a RuntimeException.
- */
- public static MapHandle map(final File file, final long fileOffsetBytes, final long capacityBytes,
- final ByteOrder byteOrder) throws IOException {
- zeroCheck(capacityBytes, "Capacity");
- nullCheck(file, "file is null");
- negativeCheck(fileOffsetBytes, "File offset is negative");
- return BaseWritableMemoryImpl.wrapMap(file, fileOffsetBytes, capacityBytes, true, byteOrder);
- }
-
//REGIONS
/**
* A region is a read-only view of this object.
@@ -200,7 +155,7 @@ public abstract class Memory extends BaseState {
* UnsupportedOperationException}.
*
* <p>The name of this method starts with "unsafe" because if this is a native managed Memory
- * (e. g. obtained via {@link #map(File)} or {@link WritableMemory#allocateDirect(long)})), and
+ * (e. g. obtained via {@link WritableMemory#allocateDirect(long)})), and
* the returned {@code ByteBuffer} object is used after the Memory is freed, it may cause a JVM
* crash. This is also possible for Memory objects themselves with some methods,
* but Memory's use-after-free is caught as an AssertionError, if assertions are enabled.
diff --git a/src/main/java/org/apache/datasketches/memory/NioBits.java b/src/main/java/org/apache/datasketches/memory/NioBits.java
deleted file mode 100644
index ac853e1..0000000
--- a/src/main/java/org/apache/datasketches/memory/NioBits.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-import static org.apache.datasketches.memory.UnsafeUtil.unsafe;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * Provide linkage to java.nio.Bits.
- *
- * @author Lee Rhodes
- */
-final class NioBits {
- private static final Class<?> VM_CLASS;
- private static final Method VM_MAX_DIRECT_MEMORY_METHOD;
- private static final Method VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD;
-
- private static final Class<?> NIO_BITS_CLASS;
- private static final Method NIO_BITS_RESERVE_MEMORY_METHOD;
- private static final Method NIO_BITS_UNRESERVE_MEMORY_METHOD;
-
- private static final AtomicLong nioBitsCount;
- private static final AtomicLong nioBitsReservedMemory;
- private static final AtomicLong nioBitsTotalCapacity;
-
- private static int pageSize = unsafe.pageSize();
- private static final long maxDBBMemory;
- private static final boolean isPageAligned;
-
- static {
- try {
- VM_CLASS = Class.forName("sun.misc.VM");
- VM_MAX_DIRECT_MEMORY_METHOD =
- VM_CLASS.getDeclaredMethod("maxDirectMemory");
- VM_MAX_DIRECT_MEMORY_METHOD.setAccessible(true);
- maxDBBMemory = (long)VM_MAX_DIRECT_MEMORY_METHOD
- .invoke(null); //static method
-
- VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD =
- VM_CLASS.getDeclaredMethod("isDirectMemoryPageAligned");
- VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD.setAccessible(true);
- isPageAligned = (boolean)VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD
- .invoke(null); //static method
-
- NIO_BITS_CLASS = Class.forName("java.nio.Bits");
-
- NIO_BITS_RESERVE_MEMORY_METHOD = NIO_BITS_CLASS
- .getDeclaredMethod("reserveMemory", long.class, int.class);
- NIO_BITS_RESERVE_MEMORY_METHOD.setAccessible(true);
-
- NIO_BITS_UNRESERVE_MEMORY_METHOD = NIO_BITS_CLASS
- .getDeclaredMethod("unreserveMemory", long.class, int.class);
- NIO_BITS_UNRESERVE_MEMORY_METHOD.setAccessible(true);
-
- final Field countField = NIO_BITS_CLASS.getDeclaredField("count");
- countField.setAccessible(true);
- nioBitsCount = (AtomicLong) (countField.get(null));
-
- final Field reservedMemoryField = NIO_BITS_CLASS.getDeclaredField("reservedMemory");
- reservedMemoryField.setAccessible(true);
- nioBitsReservedMemory = (AtomicLong) (reservedMemoryField.get(null));
-
- final Field totalCapacityField = NIO_BITS_CLASS.getDeclaredField("totalCapacity");
- totalCapacityField.setAccessible(true);
- nioBitsTotalCapacity = (AtomicLong) (totalCapacityField.get(null));
-
- } catch (final Exception e) {
- throw new RuntimeException("Could not acquire java.nio.Bits class: " + e.getClass());
- }
- }
-
- private NioBits() { }
-
- static long getDirectAllocationsCount() {
- try {
- final long count = nioBitsCount.get();
- return count;
- } catch (final Exception e) {
- throw new RuntimeException("Cannot read Bits.count " + e);
- }
- }
-
- static long getReservedMemory() {
- try {
- final long resMem = nioBitsReservedMemory.get();
- return resMem;
- } catch (final Exception e) {
- throw new RuntimeException("Cannot read Bits.reservedMemory " + e);
- }
- }
-
- static long getTotalCapacity() {
- try {
- final long resMem = nioBitsTotalCapacity.get();
- return resMem;
- } catch (final Exception e) {
- throw new RuntimeException("Cannot read Bits.totalCapacity " + e);
- }
- }
-
- static int pageSize() {
- return pageSize;
- }
-
- static int pageCount(final long bytes) {
- return (int)((bytes + pageSize()) - 1L) / pageSize();
- }
-
- static long getMaxDirectByteBufferMemory() {
- return maxDBBMemory;
- }
-
- static boolean isPageAligned() {
- return isPageAligned;
- }
-
- //RESERVE & UNRESERVE BITS MEMORY TRACKING COUNTERS
- // Comment from java.nio.Bits.java ~ line 705:
- // -XX:MaxDirectMemorySize limits the total capacity rather than the
- // actual memory usage, which will differ when buffers are page aligned.
- static void reserveMemory(final long allocationSize, final long capacity) {
- try {
- reserveUnreserve(allocationSize, capacity, NIO_BITS_RESERVE_MEMORY_METHOD);
- } catch (final Exception e) {
- throw new RuntimeException("Could not invoke java.nio.Bits.reserveMemory(...): "
- + "allocationSize = " + allocationSize + ", capacity = " + capacity, e);
- }
- }
-
- static void unreserveMemory(final long allocationSize, final long capacity) {
- try {
- reserveUnreserve(allocationSize, capacity, NIO_BITS_UNRESERVE_MEMORY_METHOD);
- } catch (final Exception e) {
- throw new RuntimeException("Could not invoke java.nio.Bits.unreserveMemory(...): "
- + "allocationSize = " + allocationSize + ", capacity = " + capacity, e);
- }
- }
-
- private static void reserveUnreserve(long allocationSize, long capacity, final Method method)
- throws Exception {
- Util.zeroCheck(capacity, "capacity");
- // 1GB is a pretty "safe" limit.
- final long chunkSizeLimit = 1L << 30;
- while (capacity > 0) {
- final long chunk = Math.min(capacity, chunkSizeLimit);
- if (capacity == chunk) {
- method.invoke(null, allocationSize, (int) capacity);
- } else {
- method.invoke(null, chunk, (int) chunk);
- }
- capacity -= chunk;
- allocationSize -= chunk;
- }
- }
-}
diff --git a/src/main/java/org/apache/datasketches/memory/UnsafeUtil.java b/src/main/java/org/apache/datasketches/memory/UnsafeUtil.java
index 9dc45f8..d99015b 100644
--- a/src/main/java/org/apache/datasketches/memory/UnsafeUtil.java
+++ b/src/main/java/org/apache/datasketches/memory/UnsafeUtil.java
@@ -19,6 +19,8 @@
package org.apache.datasketches.memory;
+//import sun.misc.Cleaner; //JDK 8
+import java.lang.ref.Cleaner; //JDK 9+
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -32,6 +34,7 @@ import sun.misc.Unsafe;
@SuppressWarnings("javadoc")
public final class UnsafeUtil {
public static final Unsafe unsafe;
+ static final Cleaner cleaner = Cleaner.create();
public static final String JDK; //must be at least "1.8"
public static final int JDK_MAJOR; //8, 9, 10, 11, 12, etc
@@ -79,6 +82,7 @@ public final class UnsafeUtil {
public static final long OBJECT_SHIFT; // varies, 2 or 3 depending on coop
public static final String LS = System.getProperty("line.separator");
+ private static int pageSize;
//@formatter:on
@@ -87,6 +91,7 @@ public final class UnsafeUtil {
final Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();
unsafeConstructor.setAccessible(true);
unsafe = unsafeConstructor.newInstance();
+ pageSize = unsafe.pageSize();
// Alternative, but may not work across different JVMs.
// Field field = Unsafe.class.getDeclaredField("theUnsafe");
@@ -119,11 +124,19 @@ public final class UnsafeUtil {
final String jdkVer = System.getProperty("java.version");
final int[] p = parseJavaVersion(jdkVer);
JDK = p[0] + "." + p[1];
- JDK_MAJOR = (p[0] == 1) ? p[1] : p[0];
+ JDK_MAJOR = p[0] == 1 ? p[1] : p[0];
}
private UnsafeUtil() {}
+ static int pageSize() {
+ return pageSize;
+ }
+
+ static int pageCount(final long bytes) {
+ return (int)(bytes + pageSize() - 1L) / pageSize();
+ }
+
/**
* Returns first two number groups of the java version string.
* @param jdkVer the java version string from System.getProperty("java.version").
@@ -135,7 +148,7 @@ public final class UnsafeUtil {
String[] parts = jdkVer.trim().split("[^0-9\\.]");//grab only number groups and "."
parts = parts[0].split("\\."); //split out the number groups
p0 = Integer.parseInt(parts[0]); //the first number group
- p1 = (parts.length > 1) ? Integer.parseInt(parts[1]) : 0; //2nd number group, or 0
+ p1 = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; //2nd number group, or 0
} catch (final Exception e) {
throw new ExceptionInInitializerError("Improper Java -version string: " + jdkVer + "\n" + e);
}
@@ -144,7 +157,7 @@ public final class UnsafeUtil {
}
static void checkJavaVersion(final String jdkVer, final int p0, final int p1) {
- if ( (p0 < 1) || ((p0 == 1) && (p1 < 8)) || (p0 >= 9) ) {
+ if ( p0 < 1 || p0 == 1 && p1 < 8 || p0 >= 9 ) {
throw new ExceptionInInitializerError(
"Unsupported JDK Major Version, must be 1.8: " + jdkVer);
}
@@ -187,6 +200,9 @@ public final class UnsafeUtil {
}
}
+
+
+
/**
* Assert the requested offset and length against the allocated size.
* The invariants equation is: {@code 0 <= reqOff <= reqLen <= reqOff + reqLen <= allocSize}.
@@ -197,7 +213,7 @@ public final class UnsafeUtil {
* @param allocSize the allocated size.
*/
public static void assertBounds(final long reqOff, final long reqLen, final long allocSize) {
- assert ((reqOff | reqLen | (reqOff + reqLen) | (allocSize - (reqOff + reqLen))) >= 0) :
+ assert (reqOff | reqLen | reqOff + reqLen | allocSize - (reqOff + reqLen)) >= 0 :
"reqOffset: " + reqOff + ", reqLength: " + reqLen
+ ", (reqOff + reqLen): " + (reqOff + reqLen) + ", allocSize: " + allocSize;
}
@@ -211,7 +227,7 @@ public final class UnsafeUtil {
* @param allocSize the allocated size.
*/
public static void checkBounds(final long reqOff, final long reqLen, final long allocSize) {
- if ((reqOff | reqLen | (reqOff + reqLen) | (allocSize - (reqOff + reqLen))) < 0) {
+ if ((reqOff | reqLen | reqOff + reqLen | allocSize - (reqOff + reqLen)) < 0) {
throw new IllegalArgumentException(
"reqOffset: " + reqOff + ", reqLength: " + reqLen
+ ", (reqOff + reqLen): " + (reqOff + reqLen) + ", allocSize: " + allocSize);
diff --git a/src/main/java/org/apache/datasketches/memory/WritableMap.java b/src/main/java/org/apache/datasketches/memory/WritableMap.java
deleted file mode 100644
index ee95578..0000000
--- a/src/main/java/org/apache/datasketches/memory/WritableMap.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-/**
- * Writable interface for a memory mapped file
- *
- * @author Roman Leventov
- * @author Lee Rhodes
- * @author Praveenkumar Venkatesan
- */
-interface WritableMap extends Map {
-
- /**
- * @see <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html#force--">
- * java/nio/MappedByteBuffer.force</a>
- */
- void force();
-
-}
diff --git a/src/main/java/org/apache/datasketches/memory/WritableMapHandle.java b/src/main/java/org/apache/datasketches/memory/WritableMapHandle.java
deleted file mode 100644
index d6cdb30..0000000
--- a/src/main/java/org/apache/datasketches/memory/WritableMapHandle.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-/**
- * A Handle for a memory-mapped, writable file resource.
- * Please read Javadocs for {@link Handle}.
- *
- * @author Roman Leventov
- * @author Lee Rhodes
- */
-//Joins a WritableHandle with an AutoCloseable WritableMap resource
-public final class WritableMapHandle extends MapHandle implements WritableMap, WritableHandle {
-
- WritableMapHandle(final AllocateDirectWritableMap dirWmap,
- final BaseWritableMemoryImpl wMem) {
- super(dirWmap, wMem);
- }
-
- @Override
- public WritableMemory get() {
- return (WritableMemory) super.get();
- }
-
- @Override
- public void force() {
- ((AllocateDirectWritableMap)dirMap).force();
- }
-}
diff --git a/src/main/java/org/apache/datasketches/memory/WritableMemory.java b/src/main/java/org/apache/datasketches/memory/WritableMemory.java
index 39eaef7..97a4b6b 100644
--- a/src/main/java/org/apache/datasketches/memory/WritableMemory.java
+++ b/src/main/java/org/apache/datasketches/memory/WritableMemory.java
@@ -19,12 +19,6 @@
package org.apache.datasketches.memory;
-import static org.apache.datasketches.memory.Util.negativeCheck;
-import static org.apache.datasketches.memory.Util.nullCheck;
-import static org.apache.datasketches.memory.Util.zeroCheck;
-
-import java.io.File;
-import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -76,45 +70,45 @@ public abstract class WritableMemory extends Memory {
return BaseWritableMemoryImpl.wrapByteBuffer(byteBuf, false, byteOrder);
}
- //MAP
- /**
- * Maps the entire given file into native-ordered Memory for write operations
- * (including those > 2GB). Calling this method is equivalent to calling
- * {@link #map(File, long, long, ByteOrder) map(file, 0, file.length(), ByteOrder.nativeOrder())}.
- *
- * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
- * <i>WritableMemory.map(...)</i>.
- * @param file the given file to map
- * @return WritableMapHandle for managing the mapped Memory.
- * Please read Javadocs for {@link Handle}.
- * @throws IOException file not found or a RuntimeException.
- */
- public static WritableMapHandle map(final File file) throws IOException {
- return map(file, 0, file.length(), BaseState.nativeByteOrder);
- }
-
- /**
- * Maps the specified portion of the given file into Memory for write operations
- * (including those > 2GB).
- *
- * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
- * <i>WritableMemory.map(...)</i>.
- * @param file the given file to map. It may not be null.
- * @param fileOffsetBytes the position in the given file in bytes. It may not be negative.
- * @param capacityBytes the size of the mapped Memory. It may not be negative or zero.
- * @param byteOrder the byte order to be used for the given file. It may not be null.
- * @return WritableMapHandle for managing the mapped Memory.
- * Please read Javadocs for {@link Handle}.
- * @throws IOException file not found or RuntimeException, etc.
- */
- public static WritableMapHandle map(final File file, final long fileOffsetBytes,
- final long capacityBytes, final ByteOrder byteOrder) throws IOException {
- zeroCheck(capacityBytes, "Capacity");
- nullCheck(file, "file is null");
- negativeCheck(fileOffsetBytes, "File offset is negative");
- return BaseWritableMemoryImpl
- .wrapMap(file, fileOffsetBytes, capacityBytes, false, byteOrder);
- }
+ // //MAP
+ // /**
+ // * Maps the entire given file into native-ordered Memory for write operations
+ // * (including those > 2GB). Calling this method is equivalent to calling
+ // * {@link #map(File, long, long, ByteOrder) map(file, 0, file.length(), ByteOrder.nativeOrder())}.
+ // *
+ // * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
+ // * <i>WritableMemory.map(...)</i>.
+ // * @param file the given file to map
+ // * @return WritableMapHandle for managing the mapped Memory.
+ // * Please read Javadocs for {@link Handle}.
+ // * @throws IOException file not found or a RuntimeException.
+ // */
+ // public static WritableMapHandle map(final File file) throws IOException {
+ // return map(file, 0, file.length(), BaseState.nativeByteOrder);
+ // }
+ //
+ // /**
+ // * Maps the specified portion of the given file into Memory for write operations
+ // * (including those > 2GB).
+ // *
+ // * <p><b>Note:</b> Always qualify this method with the class name, e.g.,
+ // * <i>WritableMemory.map(...)</i>.
+ // * @param file the given file to map. It may not be null.
+ // * @param fileOffsetBytes the position in the given file in bytes. It may not be negative.
+ // * @param capacityBytes the size of the mapped Memory. It may not be negative or zero.
+ // * @param byteOrder the byte order to be used for the given file. It may not be null.
+ // * @return WritableMapHandle for managing the mapped Memory.
+ // * Please read Javadocs for {@link Handle}.
+ // * @throws IOException file not found or RuntimeException, etc.
+ // */
+ // public static WritableMapHandle map(final File file, final long fileOffsetBytes,
+ // final long capacityBytes, final ByteOrder byteOrder) throws IOException {
+ // zeroCheck(capacityBytes, "Capacity");
+ // nullCheck(file, "file is null");
+ // negativeCheck(fileOffsetBytes, "File offset is negative");
+ // return BaseWritableMemoryImpl
+ // .wrapMap(file, fileOffsetBytes, capacityBytes, false, byteOrder);
+ // }
//ALLOCATE DIRECT
/**
diff --git a/src/main/java/org/apache/datasketches/memory/package-info.java b/src/main/java/org/apache/datasketches/memory/package-info.java
index 6cfbe5f..0c8fa19 100644
--- a/src/main/java/org/apache/datasketches/memory/package-info.java
+++ b/src/main/java/org/apache/datasketches/memory/package-info.java
@@ -19,7 +19,7 @@
/**
* <p>This package provides high performance primitive and primitive array access to direct (native),
- * off-heap memory and memory-mapped file resources, and consistent views into
+ * off-heap memory and consistent views into
* {@link java.nio.ByteBuffer}, and on-heap primitive arrays. It can be used as a more
* comprehensive and flexible replacement for {@link java.nio.ByteBuffer}.
* </p>
@@ -61,10 +61,9 @@
*
* <p>More specifically, this package provides access to four different types of resources using
* two different access APIs. These resources are contiguous blobs of bytes that provide at least
- * byte-level read and write access. The four resources are:</p>
+ * byte-level read and write access. The 3 resources are:</p>
*
* <ul><li>Direct (a.k.a. Native) off-heap memory allocated by the user.</li>
- * <li>Memory-mapped files, both writable and read-only.</li>
* <li>{@code ByteBuffers}, both heap-based and direct, writable and read-only.</li>
* <li>Heap-based primitive arrays, which can be accessed as writable or read-only.</li>
* </ul>
@@ -85,18 +84,15 @@
* <p>An access API is joined with
* a resource either with a static factory method or in combination with a
* {@link org.apache.datasketches.memory.Handle}, which is used exclusively for resources that are
- * external to the JVM, such as allocation of direct memory and memory-mapped files.</p>
+ * external to the JVM, such as allocation of direct memory.</p>
*
* <p>The role of a Handle is to hold onto the reference of a resource that is outside the control
* of the JVM. The resource is obtained from the handle with {@code get()}.</p>
*
* <p>When a handle is extended for an AutoCloseable resource and then joined with an access API
- * it becomes an <i>implementation handle</i>. There are 3 implementation handles:</p>
+ * it becomes an <i>implementation handle</i>. There is 1 implementation handle:</p>
*
- * <ul><li>{@link org.apache.datasketches.memory.MapHandle}
- * for read-only access to a memory-mapped file</li>
- * <li>{@link org.apache.datasketches.memory.WritableMapHandle}
- * for writable access to a memory-mapped file</li>
+ * <ul>
* <li>{@link org.apache.datasketches.memory.WritableDirectHandle}
* for writable access to off-heap memory.</li>
* </ul>
@@ -108,26 +104,9 @@
* in a try-with-resources (TWR) block, it's associated resource will be automatically closed by
* the JVM at the end of the block.
* The resource can also be explicitly closed by the user by calling {@code Handle.close()}.</p>
- * <blockquote><pre>
- * //Using try-with-resources block:
- * try (WritableyMapHandle handle = WritableMemory.map(File file)) {
- * WritableMemory wMem = handle.get();
- * doWork(wMem) // read and write to memory mapped file.
- * }
- *
- * //Using explicit close():
- * WritableMapHandle handle = WritableMemory.map(File file);
- * WritableMemory wMem = handle.get();
- * doWork(wMem) // read and write to memory mapped file.
- * handle.close();
- * </pre></blockquote>
*
* <p>Where it is desirable to pass ownership of the resource (and the {@code close()}
- * responsibility) one can not use the TWR block. Instead:</p>
- * <blockquote><pre>
- * WritableMapHandle handler = WritableMemory.map(File file);
- * doWorkAndClose(handle); //passes the handle to object that closes the resource.
- * </pre></blockquote>
+ * responsibility) one can not use the TWR block. </p>
*
* <p>Whatever part of your process is responsible for allocating a resource external
* to the JVM must be responsible for closing it or making sure it gets closed.
diff --git a/src/test/java/org/apache/datasketches/memory/AllocateDirectMapMemoryTest.java b/src/test/java/org/apache/datasketches/memory/AllocateDirectMapMemoryTest.java
deleted file mode 100644
index c3e2bb6..0000000
--- a/src/test/java/org/apache/datasketches/memory/AllocateDirectMapMemoryTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * Note: Lincoln's Gettysburg Address is in the public domain. See LICENSE.
- */
-
-package org.apache.datasketches.memory;
-
-import static org.apache.datasketches.memory.Util.*;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.io.File;
-import java.nio.ByteOrder;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-@SuppressWarnings("javadoc")
-public class AllocateDirectMapMemoryTest {
- private static final String LS = System.getProperty("line.separator");
- MapHandle hand = null;
-
- @BeforeClass
- public void setReadOnly() {
- UtilTest.setGettysburgAddressFileToReadOnly();
- }
-
- @Test
- public void simpleMap() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- try (MapHandle rh = Memory.map(file)) {
- rh.close();
- }
- }
-
- @Test
- public void testIllegalArguments() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- try (MapHandle rh = Memory.map(file, -1, Integer.MAX_VALUE, ByteOrder.nativeOrder())) {
- fail("Failed: testIllegalArgumentException: Position was negative.");
- } catch (IllegalArgumentException e) {
- //ok
- }
-
- try (MapHandle rh = Memory.map(file, 0, -1, ByteOrder.nativeOrder())) {
- fail("Failed: testIllegalArgumentException: Size was negative.");
- } catch (IllegalArgumentException e) {
- //ok
- }
- }
-
- @Test
- public void testMapAndMultipleClose() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long memCapacity = file.length();
- try (MapHandle rh = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) {
- Memory map = rh.get();
- assertEquals(memCapacity, map.getCapacity());
- rh.close();
- rh.close();
- map.getCapacity(); //throws assertion error
- } catch (AssertionError e) {
- //OK
- }
- }
-
- @Test
- public void testReadFailAfterClose() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long memCapacity = file.length();
- try (MapHandle rh = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) {
- Memory mmf = rh.get();
- rh.close();
- mmf.getByte(0);
- } catch (AssertionError e) {
- //OK
- }
- }
-
- @Test
- public void testLoad() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long memCapacity = file.length();
- try (MapHandle rh = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) {
- rh.load();
- assertTrue(rh.isLoaded());
- rh.close();
- }
- }
-
- @Test
- public void testHandlerHandoffWithTWR() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long memCapacity = file.length();
- Memory mem;
- try (MapHandle rh = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) {
- rh.load();
- assertTrue(rh.isLoaded());
- hand = rh;
- mem = rh.get();
- } //TWR closes
- assertFalse(mem.isValid());
- //println(""+mem.isValid());
- }
-
- @Test
- public void testHandoffWithoutClose() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long memCapacity = file.length();
- MapHandle rh = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder());
- rh.load();
- assertTrue(rh.isLoaded());
- hand = rh;
- //The receiver of the handler must close the resource, in this case it is the class.
- }
-
- @AfterClass
- public void afterAllTests() {
- if (hand != null) {
- Memory mem = hand.get();
- if ((mem != null) && mem.isValid()) {
- hand.close();
- assertFalse(mem.isValid());
- }
- }
- }
-
- @Test
- public void printlnTest() {
- println("PRINTING: "+this.getClass().getName());
- }
-
- static void println(final Object o) {
- if (o == null) { print(LS); }
- else { print(o.toString() + LS); }
- }
-
- /**
- * @param o value to print
- */
- static void print(final Object o) {
- if (o != null) {
- //System.out.print(o.toString()); //disable here
- }
- }
-
-}
diff --git a/src/test/java/org/apache/datasketches/memory/AllocateDirectWritableMapMemoryTest.java b/src/test/java/org/apache/datasketches/memory/AllocateDirectWritableMapMemoryTest.java
deleted file mode 100644
index bdf361f..0000000
--- a/src/test/java/org/apache/datasketches/memory/AllocateDirectWritableMapMemoryTest.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * Note: Lincoln's Gettysburg Address is in the public domain. See LICENSE.
- */
-
-package org.apache.datasketches.memory;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.apache.datasketches.memory.AllocateDirectMap.isFileReadOnly;
-import static org.apache.datasketches.memory.Util.getResourceFile;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteOrder;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-@SuppressWarnings("javadoc")
-public class AllocateDirectWritableMapMemoryTest {
- private static final String LS = System.getProperty("line.separator");
-
- @BeforeClass
- public void setReadOnly() {
- UtilTest.setGettysburgAddressFileToReadOnly();
- }
-
- @Test
- public void simpleMap() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- try (MapHandle h = Memory.map(file); WritableMapHandle wh = (WritableMapHandle) h) {
- Memory mem = h.get();
- byte[] bytes = new byte[(int)mem.getCapacity()];
- mem.getByteArray(0, bytes, 0, bytes.length);
- String text = new String(bytes, UTF_8);
- println(text);
- try {
- wh.force();
- fail();
- } catch (ReadOnlyException e) {
- //OK
- }
- }
- }
-
- @Test
- public void copyOffHeapToMemoryMappedFile() throws Exception {
- long bytes = 1L << 10; //small for unit tests. Make it larger than 2GB if you like.
- long longs = bytes >>> 3;
-
- File file = new File("TestFile.bin");
- if (file.exists()) {
- try {
- java.nio.file.Files.delete(file.toPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- assertTrue(file.createNewFile());
- assertTrue (file.setWritable(true, false)); //writable=true, ownerOnly=false
- assertTrue (file.isFile());
- file.deleteOnExit(); //comment out if you want to examine the file.
-
- try (
- WritableMapHandle dstHandle
- = WritableMemory.map(file, 0, bytes, ByteOrder.nativeOrder());
- WritableHandle srcHandle = WritableMemory.allocateDirect(bytes)) {
-
- WritableMemory dstMem = dstHandle.get();
- WritableMemory srcMem = srcHandle.get();
-
- for (long i = 0; i < longs; i++) {
- srcMem.putLong(i << 3, i); //load source with consecutive longs
- }
-
- srcMem.copyTo(0, dstMem, 0, srcMem.getCapacity()); //off-heap to off-heap copy
-
- dstHandle.force(); //push any remaining to the file
-
- //check end value
- assertEquals(dstMem.getLong(longs - 1L << 3), longs - 1L);
- }
- }
-
- @Test
- public void checkNonNativeFile() throws IOException {
- File file = new File("TestFile2.bin");
- if (file.exists()) {
- try {
- java.nio.file.Files.delete(file.toPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- assertTrue(file.createNewFile());
- assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false
- assertTrue(file.isFile());
- file.deleteOnExit(); //comment out if you want to examine the file.
-
- final long bytes = 8;
- try (WritableMapHandle h = WritableMemory.map(file, 0L, bytes, BaseState.nonNativeByteOrder)) {
- WritableMemory wmem = h.get();
- wmem.putChar(0, (char) 1);
- assertEquals(wmem.getByte(1), (byte) 1);
- }
- }
-
- @SuppressWarnings("resource")
- @Test(expectedExceptions = RuntimeException.class)
- public void testMapException() throws IOException {
- File dummy = createFile("dummy.txt", ""); //zero length
- //throws java.lang.reflect.InvocationTargetException
- Memory.map(dummy, 0, dummy.length(), ByteOrder.nativeOrder());
- }
-
- @Test(expectedExceptions = ReadOnlyException.class)
- public void simpleMap2() throws IOException {
- File file = getResourceFile("GettysburgAddress.txt");
- assertTrue(isFileReadOnly(file));
- try (WritableMapHandle rh = WritableMemory.map(file)) {
- //
- }
- }
-
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void checkOverLength() {
- File file = getResourceFile("GettysburgAddress.txt");
- try (WritableMapHandle rh = WritableMemory.map(file, 0, 1 << 20, ByteOrder.nativeOrder())) {
- //
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testForce() throws Exception {
- String origStr = "Corectng spellng mistks";
- File origFile = createFile("force_original.txt", origStr); //23
- assertTrue(origFile.setWritable(true, false));
- long origBytes = origFile.length();
- String correctStr = "Correcting spelling mistakes"; //28
- byte[] correctByteArr = correctStr.getBytes(UTF_8);
- long corrBytes = correctByteArr.length;
-
- try (MapHandle rh = Memory.map(origFile, 0, origBytes, ByteOrder.nativeOrder())) {
- Memory map = rh.get();
- rh.load();
- assertTrue(rh.isLoaded());
- //confirm orig string
- byte[] buf = new byte[(int)origBytes];
- map.getByteArray(0, buf, 0, (int)origBytes);
- String bufStr = new String(buf, UTF_8);
- assertEquals(bufStr, origStr);
- }
-
- try (WritableMapHandle wrh = WritableMemory.map(origFile, 0, corrBytes,
- ByteOrder.nativeOrder())) {
- WritableMemory wMap = wrh.get();
- wrh.load();
- assertTrue(wrh.isLoaded());
- // over write content
- wMap.putByteArray(0, correctByteArr, 0, (int)corrBytes);
- wrh.force();
- //confirm correct string
- byte[] buf = new byte[(int)corrBytes];
- wMap.getByteArray(0, buf, 0, (int)corrBytes);
- String bufStr = new String(buf, UTF_8);
- assertEquals(bufStr, correctStr);
- }
- }
-
- private static File createFile(String fileName, String text) throws FileNotFoundException {
- File file = new File(fileName);
- file.deleteOnExit();
- PrintWriter writer;
- try {
- writer = new PrintWriter(file, UTF_8.name());
- writer.print(text);
- writer.close();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return file;
- }
-
- @Test
- public void checkExplicitClose() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- try (MapHandle wmh = Memory.map(file)) {
- wmh.close(); //explicit close. Does the work of closing
- wmh.dirMap.close(); //redundant
- } //end of scope call to Cleaner/Deallocator also will be redundant
- }
-
- @AfterClass
- public void checkMapCounter() {
- final long count = BaseState.getCurrentDirectMemoryMapAllocations();
- if (count != 0) {
- println(""+count);
- fail();
- }
- }
-
- @Test
- public void printlnTest() {
- println("PRINTING: "+this.getClass().getName());
- }
-
- static void println(final Object o) {
- if (o == null) { print(LS); }
- else { print(o.toString() + LS); }
- }
-
- /**
- * @param o value to print
- */
- static void print(final Object o) {
- if (o != null) {
- //System.out.print(o.toString()); //disable here
- }
- }
-
-}
diff --git a/src/test/java/org/apache/datasketches/memory/LeafImplTest.java b/src/test/java/org/apache/datasketches/memory/LeafImplTest.java
index 696a95d..58fe24f 100644
--- a/src/test/java/org/apache/datasketches/memory/LeafImplTest.java
+++ b/src/test/java/org/apache/datasketches/memory/LeafImplTest.java
@@ -25,8 +25,6 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -108,86 +106,7 @@ public class LeafImplTest {
assertTrue(nnBuf.isValid() == true);
}
- @Test
- public void checkMapLeafs() throws IOException {
- long off = 0;
- long cap = 128;
- File file = new File("TestFile2.bin");
- if (file.exists()) {
- try {
- java.nio.file.Files.delete(file.toPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- assertTrue(file.createNewFile());
- assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false
- assertTrue(file.isFile());
- file.deleteOnExit(); //comment out if you want to examine the file.
-
- try (WritableMapHandle wmh = WritableMemory.map(file, off, cap, BaseState.nativeByteOrder)) {
- WritableMemory mem = wmh.get();
- mem.putShort(0, (short) 1);
- assertEquals(mem.getByte(0), (byte) 1);
- checkMapImpl(mem, off, cap);
- }
- }
-
- private static void checkMapImpl(WritableMemory mem, long off, long cap) {
- assertEquals(mem.writableRegion(off, cap, LE).getShort(0), 1);
- assertEquals(mem.writableRegion(off, cap, BE).getShort(0), 256);
- assertEquals(mem.asWritableBuffer(LE).getShort(0), 1);
- assertEquals(mem.asWritableBuffer(BE).getShort(0), 256);
-
- assertTrue(mem.getByteBuffer() == null);
- assertTrue(mem.getTypeByteOrder() == BaseState.nativeByteOrder);
- assertTrue(mem.getMemoryRequestServer() == null);
- assertTrue(mem.isDirect());
- assertTrue(mem.getUnsafeObject() == null);
- assertTrue(mem.isValid() == true);
-
- WritableBuffer buf = mem.asWritableBuffer();
-
- assertEquals(buf.writableRegion(off, cap, LE).getShort(0), 1);
- assertEquals(buf.writableRegion(off, cap, BE).getShort(0), 256);
- assertEquals(buf.writableDuplicate(LE).getShort(0), 1);
- assertEquals(buf.writableDuplicate(BE).getShort(0), 256);
-
- assertTrue(buf.getByteBuffer() == null);
- assertTrue(buf.getTypeByteOrder() == BaseState.nativeByteOrder);
- assertTrue(buf.getMemoryRequestServer() == null);
- assertTrue(buf.isDirect());
- assertTrue(buf.getUnsafeObject() == null);
- assertTrue(buf.isValid() == true);
-
- WritableMemory nnMem = mem.writableRegion(off, cap, BaseState.nonNativeByteOrder);
-
- assertEquals(nnMem.writableRegion(off, cap, LE).getShort(0), 1);
- assertEquals(nnMem.writableRegion(off, cap, BE).getShort(0), 256);
- assertEquals(nnMem.asWritableBuffer(LE).getShort(0), 1);
- assertEquals(nnMem.asWritableBuffer(BE).getShort(0), 256);
-
- assertTrue(nnMem.getByteBuffer() == null);
- assertTrue(nnMem.getTypeByteOrder() == BaseState.nonNativeByteOrder);
- assertTrue(nnMem.getMemoryRequestServer() == null);
- assertTrue(nnMem.isDirect());
- assertTrue(nnMem.getUnsafeObject() == null);
- assertTrue(nnMem.isValid() == true);
-
- WritableBuffer nnBuf = mem.asWritableBuffer(BaseState.nonNativeByteOrder);
-
- assertEquals(nnBuf.writableRegion(off, cap, LE).getShort(0), 1);
- assertEquals(nnBuf.writableRegion(off, cap, BE).getShort(0), 256);
- assertEquals(nnBuf.writableDuplicate(LE).getShort(0), 1);
- assertEquals(nnBuf.writableDuplicate(BE).getShort(0), 256);
- assertTrue(nnBuf.getByteBuffer() == null);
- assertTrue(nnBuf.getTypeByteOrder() == BaseState.nonNativeByteOrder);
- assertTrue(nnBuf.getMemoryRequestServer() == null);
- assertTrue(nnBuf.isDirect());
- assertTrue(nnBuf.getUnsafeObject() == null);
- assertTrue(nnBuf.isValid() == true);
- }
@Test
public void checkByteBufferLeafs() {
diff --git a/src/test/java/org/apache/datasketches/memory/MemoryReadWriteSafetyTest.java b/src/test/java/org/apache/datasketches/memory/MemoryReadWriteSafetyTest.java
index 19aab85..9ae3004 100644
--- a/src/test/java/org/apache/datasketches/memory/MemoryReadWriteSafetyTest.java
+++ b/src/test/java/org/apache/datasketches/memory/MemoryReadWriteSafetyTest.java
@@ -19,9 +19,6 @@
package org.apache.datasketches.memory;
-import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -188,38 +185,4 @@ public class MemoryReadWriteSafetyTest {
mem1.putInt(0, 1);
}
- //@SuppressWarnings("resource")
- @Test(expectedExceptions = AssertionError.class)
- public void testMapFile() throws IOException {
- File tempFile = File.createTempFile("test", null);
- tempFile.deleteOnExit();
- try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw")) {
- raf.setLength(8);
- //System.out.println(UtilTest.getFileAttributes(tempFile));
- try (MapHandle h = Memory.map(tempFile)) {
- ((WritableMemory) h.get()).putInt(0, 1);
- }
- }
- }
-
- @SuppressWarnings("resource")
- @Test(expectedExceptions = AssertionError.class)
- public void testMapFileWithOffsetsAndBO() throws IOException {
- File tempFile = File.createTempFile("test", "test");
- tempFile.deleteOnExit();
- new RandomAccessFile(tempFile, "rw").setLength(8);
- try (MapHandle h = Memory.map(tempFile, 0, 4, ByteOrder.nativeOrder())) {
- ((WritableMemory) h.get()).putInt(0, 1);
- }
- }
-
- @SuppressWarnings("resource")
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void testMapFileBeyondTheFileSize() throws IOException {
- File tempFile = File.createTempFile("test", "test");
- tempFile.deleteOnExit();
- new RandomAccessFile(tempFile, "rw").setLength(8);
- try (MapHandle unused = Memory.map(tempFile, 0, 16, ByteOrder.nativeOrder())) {
- }
- }
}
diff --git a/src/test/java/org/apache/datasketches/memory/MemoryTest.java b/src/test/java/org/apache/datasketches/memory/MemoryTest.java
index d70e6fd..15f3f67 100644
--- a/src/test/java/org/apache/datasketches/memory/MemoryTest.java
+++ b/src/test/java/org/apache/datasketches/memory/MemoryTest.java
@@ -23,14 +23,12 @@
package org.apache.datasketches.memory;
-import static org.apache.datasketches.memory.Util.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
-import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
@@ -396,28 +394,6 @@ public class MemoryTest {
assertEquals(BaseState.getCurrentDirectMemoryAllocated(), 0L);
}
- @SuppressWarnings("resource")
- @Test
- public void checkMonitorDirectMapStats() throws Exception {
- File file = getResourceFile("GettysburgAddress.txt");
- long bytes = file.length();
-
- MapHandle mmh1 = Memory.map(file);
- MapHandle mmh2 = Memory.map(file);
-
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 2L);
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), 2 * bytes);
-
- mmh1.close();
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 1L);
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), bytes);
-
- mmh2.close();
- mmh2.close(); //check that it doesn't go negative.
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 0L);
- assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), 0L);
- }
-
@Test
public void checkNullMemReqSvr() {
WritableMemory wmem = WritableMemory.wrap(new byte[16]);
diff --git a/src/test/java/org/apache/datasketches/memory/NioBitsTest.java b/src/test/java/org/apache/datasketches/memory/NioBitsTest.java
deleted file mode 100644
index 4e08487..0000000
--- a/src/test/java/org/apache/datasketches/memory/NioBitsTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.datasketches.memory;
-
-import static org.testng.Assert.assertEquals;
-
-import org.testng.annotations.Test;
-
-/**
- * @author Lee Rhodes
- */
-@SuppressWarnings("javadoc")
-public class NioBitsTest {
-
- @Test
- public void checkVMParams() {
- println("Max Memory: " + NioBits.getMaxDirectByteBufferMemory());
- println("Page Aligned: " + NioBits.isPageAligned());
- println("Page Size: " + NioBits.pageSize());
- }
-
- @Test
- //testing this beyond 2GB may not work on JVMs < 8GB.
- //This must be checked manually
- public void checkGetAtomicFields() {
- long cap = 1024L + Integer.MAX_VALUE;
- printStats();
- NioBits.reserveMemory(cap, cap);
- printStats();
- NioBits.unreserveMemory(cap, cap);
- printStats();
- }
-
- @Test
- public void checkPageCount() {
- assertEquals(NioBits.pageCount(0), 0);
- assertEquals(NioBits.pageCount(1), 1);
- }
-
- private static void printStats() {
- long count = NioBits.getDirectAllocationsCount();
- long resMem = NioBits.getReservedMemory();
- long totCap = NioBits.getTotalCapacity();
- long maxDBBmem = NioBits.getMaxDirectByteBufferMemory();
- String s = String.format("%,10d\t%,15d\t%,15d\t%,15d", count, resMem, totCap, maxDBBmem);
- println(s);
- }
-
-
- @Test
- public void printlnTest() {
- println("PRINTING: " + this.getClass().getName());
- }
-
- /**
- * @param s value to print
- */
- static void println(final String s) {
- //System.out.println(s); //disable here
- }
-
-}
diff --git a/src/test/java/org/apache/datasketches/memory/SpecificLeafTest.java b/src/test/java/org/apache/datasketches/memory/SpecificLeafTest.java
index 04136b8..b62cc47 100644
--- a/src/test/java/org/apache/datasketches/memory/SpecificLeafTest.java
+++ b/src/test/java/org/apache/datasketches/memory/SpecificLeafTest.java
@@ -24,8 +24,6 @@ import static org.apache.datasketches.memory.BaseState.REGION;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
import java.nio.ByteBuffer;
import org.testng.annotations.Test;
@@ -87,47 +85,6 @@ public class SpecificLeafTest {
}
@Test
- public void checkMapLeafs() throws IOException {
- File file = new File("TestFile2.bin");
- if (file.exists()) {
- try {
- java.nio.file.Files.delete(file.toPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- assertTrue(file.createNewFile());
- assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false
- assertTrue(file.isFile());
- file.deleteOnExit(); //comment out if you want to examine the file.
-
- final long bytes = 128;
-
- try (WritableMapHandle h = WritableMemory.map(file, 0L, bytes, BaseState.nativeByteOrder)) {
- WritableMemory mem = h.get(); //native mem
- assertTrue(mem.isMapType());
- assertFalse(mem.isReadOnly());
- checkCrossLeafTypeIds(mem);
- Memory nnreg = mem.region(0, bytes, BaseState.nonNativeByteOrder);
-
- Memory reg = mem.region(0, bytes, BaseState.nativeByteOrder);
- Buffer buf = reg.asBuffer().region(0, bytes, BaseState.nativeByteOrder);
- Buffer buf4 = buf.duplicate();
-
- Memory reg2 = nnreg.region(0, bytes, BaseState.nonNativeByteOrder);
- Buffer buf2 = reg2.asBuffer().region(0, bytes, BaseState.nonNativeByteOrder);
- Buffer buf3 = buf2.duplicate();
-
- assertTrue((reg.getTypeId() & REGION) > 0);
- assertTrue((reg2.getTypeId() & REGION) > 0);
- assertTrue((buf.getTypeId() & REGION) > 0);
- assertTrue((buf2.getTypeId() & REGION) > 0);
- assertTrue((buf3.getTypeId() & DUPLICATE) > 0);
- assertTrue((buf4.getTypeId() & DUPLICATE) > 0);
- }
- }
-
- @Test
public void checkHeapLeafs() {
int bytes = 128;
Memory mem = Memory.wrap(new byte[bytes]);
diff --git a/src/test/java/org/apache/datasketches/memory/UnsafeUtilTest.java b/src/test/java/org/apache/datasketches/memory/UnsafeUtilTest.java
index e571d59..ef16ea8 100644
--- a/src/test/java/org/apache/datasketches/memory/UnsafeUtilTest.java
+++ b/src/test/java/org/apache/datasketches/memory/UnsafeUtilTest.java
@@ -156,6 +156,12 @@ public class UnsafeUtilTest {
}
@Test
+ public void checkPageCount() {
+ assertEquals(UnsafeUtil.pageCount(0), 0);
+ assertEquals(UnsafeUtil.pageCount(1), 1);
+ }
+
+ @Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
diff --git a/src/test/java/org/apache/datasketches/memory/Utf8Test.java b/src/test/java/org/apache/datasketches/memory/Utf8Test.java
index 3f66508..8910c2a 100644
--- a/src/test/java/org/apache/datasketches/memory/Utf8Test.java
+++ b/src/test/java/org/apache/datasketches/memory/Utf8Test.java
@@ -28,10 +28,10 @@ import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
+import org.apache.datasketches.memory.Util.RandomCodePoints;
import org.testng.annotations.Test;
import com.google.protobuf.ByteString;
-import org.apache.datasketches.memory.Util.RandomCodePoints;
/**
* Adapted version of
@@ -133,7 +133,7 @@ public class Utf8Test {
// Test all 1, 2, 3 invalid byte combinations. Valid ones would have been covered above.
- @Test
+ //@Test //Uses ProtoBuf
public void testOneByte() {
int valid = 0;
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
@@ -147,7 +147,7 @@ public class Utf8Test {
assertEquals(IsValidUtf8TestUtil.EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, valid);
}
- @Test
+ //@Test //Uses ProtoBuf
public void testTwoBytes() {
int valid = 0;
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
@@ -163,7 +163,7 @@ public class Utf8Test {
assertEquals(IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT, valid);
}
- //@Test
+ //@Test //Uses ProtoBuf
//This test is very long, and doesn't cover the 4-byte combinations.
// This is replaced by the test following which does cover some 4-byte combinations.
public void testThreeBytes() {
@@ -182,8 +182,8 @@ public class Utf8Test {
valid++;
}
count++;
- if ((count % 1000000L) == 0) {
- println("Processed " + (count / 1000000L) + " million characters");
+ if (count % 1000000L == 0) {
+ println("Processed " + count / 1000000L + " million characters");
}
}
}
@@ -483,7 +483,7 @@ public class Utf8Test {
}
private static boolean isSurrogateCodePoint(final int cp) {
- return (cp >= Character.MIN_SURROGATE) && (cp <= Character.MAX_SURROGATE);
+ return cp >= Character.MIN_SURROGATE && cp <= Character.MAX_SURROGATE;
}
private static void checkStrings(String actual, String expected) {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datasketches.apache.org
For additional commands, e-mail: commits-help@datasketches.apache.org