This is an automated email from the ASF dual-hosted git repository.
leerho pushed a commit to branch update_3.1.X
in repository https://gitbox.apache.org/repos/asf/datasketches-memory.git
The following commit(s) were added to refs/heads/update_3.1.X by this push:
new 60a8deab Update 3.1.X
60a8deab is described below
commit 60a8deabe99886ea90c0b795d29ae0a3eb2a9658
Author: Lee Rhodes <[email protected]>
AuthorDate: Thu May 7 11:24:49 2026 -0700
Update 3.1.X
---
datasketches-memory-java11/pom.xml | 6 +-
.../memory/internal/AllocateDirect.java | 6 +-
.../memory/internal/AllocateDirectWritableMap.java | 66 ++++-------
.../memory/internal/BaseWritableMemoryImpl.java | 4 +-
.../memory/internal/MemoryCleaner.java | 51 --------
.../datasketches/memory/internal/ResourceImpl.java | 7 --
.../datasketches/memory/internal/StepBoolean.java | 33 +++---
.../apache/datasketches/memory/internal/Util.java | 22 ++--
.../internal/ExampleMemoryRequestServerTest.java | 1 -
.../memory/internal/MemoryCleanerTest.java | 62 ----------
datasketches-memory-java21/pom.xml | 42 +++----
.../org/apache/datasketches/memory/Memory.java | 2 +-
.../org/apache/datasketches/memory/Resource.java | 59 ----------
.../apache/datasketches/memory/WritableMemory.java | 2 +-
.../memory/internal/AllocateDirect.java | 115 ++++++++----------
.../memory/internal/BaseWritableMemoryImpl.java | 4 +-
.../memory/internal/MemoryCleaner.java | 51 --------
.../datasketches/memory/internal/ResourceImpl.java | 27 +----
.../datasketches/memory/internal/StepBoolean.java | 33 +++---
.../datasketches/memory/internal/UnsafeUtil.java | 5 -
.../apache/datasketches/memory/internal/Util.java | 129 ---------------------
.../memory/internal/VirtualMachineMemory.java | 56 ---------
.../internal/ExampleMemoryRequestServerTest.java | 1 -
.../memory/internal/MemoryCleanerTest.java | 62 ----------
.../datasketches/memory/internal/MemoryTest.java | 6 -
.../datasketches/memory/internal/UtilTest.java | 74 +-----------
.../memory/internal/ZeroCapacityTest.java | 2 +-
.../src/test/resources/GettysburgAddress.txt | 7 --
tools/scripts/assets/CheckMemoryJar.java | 19 +--
29 files changed, 165 insertions(+), 789 deletions(-)
diff --git a/datasketches-memory-java11/pom.xml
b/datasketches-memory-java11/pom.xml
index 2a1ce83c..c8c669a4 100644
--- a/datasketches-memory-java11/pom.xml
+++ b/datasketches-memory-java11/pom.xml
@@ -47,8 +47,6 @@ under the License.
<maven.compiler.showWarnings>true</maven.compiler.showWarnings>
<!-- jdk.internal.misc is used to call public Unsafe & public VM -->
<arg.jdk.internal.misc>--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED</arg.jdk.internal.misc>
- <!-- jdk.internal.ref is used to call public Cleaner -->
-
<arg.jdk.internal.ref>--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED</arg.jdk.internal.ref>
<!-- sun.nio.ch.exports is used to open FileChannelImpl for DirectBuffer-->
<arg.sun.nio.ch.exports>--add-exports=java.base/sun.nio.ch=ALL-UNNAMED</arg.sun.nio.ch.exports>
<!-- sun.nio.ch.opens is used to open FileChannelImpl for map0 & unmap0
for reflection-->
@@ -97,7 +95,7 @@ under the License.
<configuration>
<fork>true</fork> <!-- required if Maven is using a different JVM -->
<compilerArgs>
- <arg>${arg.jdk.internal.ref}</arg>
+ <!-- <arg>${arg.jdk.internal.ref}</arg> -->
<arg>${arg.jdk.internal.misc}</arg>
<arg>${arg.sun.nio.ch.exports}</arg>
<arg>${arg.sun.nio.ch.opens}</arg>
@@ -115,7 +113,7 @@ under the License.
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
- @{argLine} @{jvm.args} ${arg.java.nio} ${arg.sun.nio.ch.exports}
${arg.sun.nio.ch.opens} ${arg.jdk.internal.misc} ${arg.jdk.internal.ref}
+ @{argLine} @{jvm.args} ${arg.java.nio} ${arg.sun.nio.ch.exports}
${arg.sun.nio.ch.opens} ${arg.jdk.internal.misc}
</argLine>
<trimStackTrace>false</trimStackTrace>
<useFile>false</useFile>
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
index b93aae08..350678e4 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
@@ -48,9 +48,9 @@ public class AllocateDirect {
* @param capacityBytes must be greater than or equal 0.
* @param alignment the desired alignment. It must be a power of 2; e.g., 2,
4 or 8; and greater than 1.
*/
- AllocateDirect(final long capacityBytes, int alignment) {
+ AllocateDirect(final long capacityBytes, final int alignment) {
if (capacityBytes < 0) { throw new IllegalArgumentException("capacityBytes
must be >= 0: " + capacityBytes); }
- long mask = alignment - 1L;
+ final long mask = alignment - 1L;
if (checkAlignment(alignment)) {
throw new IllegalArgumentException("alignment must be a positive power
of 2 and greater than one: " + alignment); }
try {
@@ -104,6 +104,6 @@ public class AllocateDirect {
* @return true if argument is greater than one and a positive power of 2.
*/
private static final boolean checkAlignment(final int n) {
- return (n >= 1) && ((n & -n) == n);
+ return (n > 1) && ((n & -n) == n);
}
}
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirectWritableMap.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirectWritableMap.java
index eacf63b8..de99ef68 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirectWritableMap.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/AllocateDirectWritableMap.java
@@ -25,6 +25,7 @@ import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
+import java.lang.ref.Cleaner; // Standard Java 9+ Cleaner
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
@@ -45,13 +46,11 @@ import sun.nio.ch.FileChannelImpl;
* <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
*/
-//@SuppressWarnings("restriction")
final class AllocateDirectWritableMap {
static final Logger LOG =
Logger.getLogger(AllocateDirectWritableMap.class.getCanonicalName());
+ private static final Cleaner CLEANER = Cleaner.create();
private static final int MAP_RO = 0;
private static final int MAP_RW = 1;
@@ -74,18 +73,17 @@ final class AllocateDirectWritableMap {
.getDeclaredMethod("unmap0", long.class, long.class); //OK through
jDK16
FILE_CHANNEL_IMPL_UNMAP0_METHOD.setAccessible(true);
-
//The MappedByteBuffer methods load0, isLoaded0 and force0 are removed
in 15
MAPPED_BYTE_BUFFER_LOAD0_METHOD = MappedByteBuffer.class
- .getDeclaredMethod("load0", long.class, long.class); //JDK15 removed
+ .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);
//JDK15 removed
+ .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); //JDK15 removed
+ .getDeclaredMethod("force0", FileDescriptor.class, long.class,
long.class);
MAPPED_BYTE_BUFFER_FORCE0_METHOD.setAccessible(true);
} catch (final SecurityException | NoSuchMethodException e) {
throw new RuntimeException("Could not reflect static methods: " + e);
@@ -93,7 +91,7 @@ final class AllocateDirectWritableMap {
}
private final Deallocator deallocator;
- private final MemoryCleaner cleaner;
+ private final Cleaner.Cleanable cleanable;
private final File file;
final long capacityBytes;
@@ -101,12 +99,13 @@ final class AllocateDirectWritableMap {
final long nativeBaseOffset;
final boolean resourceReadOnly;
- AllocateDirectWritableMap(final File file, final long fileOffsetBytes, final
long capacityBytes,
+ AllocateDirectWritableMap(final File file, final long fileOffsetBytes, final
long capacityBytes,
final boolean localReadOnly) {
this.file = file;
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: "
@@ -115,21 +114,16 @@ final class AllocateDirectWritableMap {
}
raf = mapper(file, fileOffsetBytes, capacityBytes, resourceReadOnly);
nativeBaseOffset = map(raf.getChannel(), resourceReadOnly,
fileOffsetBytes, capacityBytes);
+
deallocator = new Deallocator(nativeBaseOffset, capacityBytes, raf);
- cleaner = new MemoryCleaner(this, deallocator);
+ cleanable = CLEANER.register(this, deallocator);
}
public void close() {
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();
- }
-
- } catch (final Exception e) { throw new IllegalStateException("Attempted
close of Memory-Mapped File: "
- + file.getName() + " " + e);
+ cleanable.clean(); //triggers the deallocator and ensures it only runs
once
+ } catch (final Exception e) {
+ throw new IllegalStateException("Attempted close of Memory-Mapped File:
" + file.getName() + " " + e);
} finally {
ResourceImpl.reachabilityFence(this);
}
@@ -253,58 +247,40 @@ final class AllocateDirectWritableMap {
}
}
+ // The Deallocator must NOT have a reference to the
AllocateDirectWritableMap.
+ // Otherwise, it would block a GC.
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
+ private final StepBoolean valid = new StepBoolean(true);
- Deallocator(final long nativeBaseOffset, final long capacityBytes,
- final RandomAccessFile raf) {
+ Deallocator(final long nativeBaseOffset, final long capacityBytes, final
RandomAccessFile raf) {
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() throws IllegalStateException {
- deallocate(true);
- }
-
- boolean deallocate(final boolean calledFromCleaner) throws
IllegalStateException {
+ public void run() {
if (valid.change()) {
- if (calledFromCleaner) {
- // Warn about non-deterministic resource cleanup.
- LOG.warning("A direct mapped resource was not closed explicitly");
- }
unmap();
- return true;
}
- 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 IllegalStateException {
+ private void unmap() {
try {
FILE_CHANNEL_IMPL_UNMAP0_METHOD.invoke(myFc, actualNativeBaseOffset,
myCapacity);
myRaf.close();
- } catch (final IllegalAccessException | IllegalArgumentException |
InvocationTargetException | IOException e) {
+ } catch (final Exception e) {
throw new IllegalStateException(String.format("Encountered %s
exception while freeing memory", e.getClass()));
}
}
} //End of class Deallocator
-
}
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
index 81c2464e..b7aefd79 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
@@ -299,8 +299,8 @@ public abstract class BaseWritableMemoryImpl extends
ResourceImpl implements Wri
}
@Override
- public final void writeTo(final long offsetBytes, final long lengthBytes,
- final WritableByteChannel out) throws IOException {
+ public final void writeTo(final long offsetBytes, final long lengthBytes,
final WritableByteChannel out)
+ throws IOException {
checkValidAndBounds(offsetBytes, lengthBytes);
if (getUnsafeObject() instanceof byte[]) {
writeByteArrayTo((byte[]) getUnsafeObject(), offsetBytes, lengthBytes,
out);
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
deleted file mode 100644
index fd21f119..00000000
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
+++ /dev/null
@@ -1,51 +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.internal;
-
-import jdk.internal.ref.Cleaner;
-
-/**
- * Extracts a version-dependent reference to the `jdk.internal.ref.Cleaner`
into
- * a standalone class. The package name for Cleaner has changed in
- * later versions. The appropriate class will be loaded by the class loader
- * depending on the Java version that is used.
- * For more information, see: https://openjdk.java.net/jeps/238
- */
-//@SuppressWarnings("restriction")
-public class MemoryCleaner {
- private final Cleaner cleaner;
-
- /**
- * Creates a new `jdk.internal.ref.Cleaner`.
- * @param referent the object to be cleaned
- * @param deallocator - the cleanup code to be run when the cleaner is
invoked.
- * return MemoryCleaner
- */
- public MemoryCleaner(final Object referent, final Runnable deallocator) {
- cleaner = Cleaner.create(referent, deallocator);
- }
-
- /**
- * Runs this cleaner, if it has not been run before.
- */
- public void clean() {
- cleaner.clean();
- }
-}
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
index 5eaf3915..b970476a 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
@@ -81,8 +81,6 @@ public abstract class ResourceImpl implements Resource {
static final String NOT_MAPPED_FILE_RESOURCE = "This is not a memory-mapped
file resource";
static final String THREAD_EXCEPTION_TEXT = "Attempted access outside owning
thread";
-
- private static boolean JAVA_VERSION_WARNING_PRINTED = false;
static {
final String jdkVer = System.getProperty("java.version");
@@ -157,11 +155,6 @@ public abstract class ResourceImpl implements Resource {
if (!ok) { throw new IllegalArgumentException(
"Unsupported JDK Major Version. It must be one of 1.8, 8, 11, 17, 21,
25: " + jdkVer);
}
- if (p0 > 11 && !JAVA_VERSION_WARNING_PRINTED) {
- System.err.println(
- "Warning: Java versions > Java 11 can only operate in restricted
mode where no off-heap operations are allowed!");
- JAVA_VERSION_WARNING_PRINTED = true;
- }
}
void checkNotReadOnly() {
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
index 45f81c35..e6f352de 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
@@ -19,29 +19,33 @@
package org.apache.datasketches.memory.internal;
-import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
/**
- * This is a step boolean function that can change its state only once.
+ * This is a step boolean or latch function that can change its state only
once.
*
* @author Lee Rhodes
*/
public final class StepBoolean {
- private static final int FALSE = 0;
- private static final int TRUE = 1;
- private static final AtomicIntegerFieldUpdater<StepBoolean>
STATE_FIELD_UPDATER =
- AtomicIntegerFieldUpdater.newUpdater(StepBoolean.class, "state");
+ private static final VarHandle STATE_HANDLE;
+
+ static {
+ try {
+ STATE_HANDLE =
MethodHandles.lookup().findVarHandle(StepBoolean.class, "state", int.class);
+ } catch (final ReflectiveOperationException e) { throw new Error(e); }
+ }
private final int initialState;
- private volatile int state;
+ private volatile int state; // Still needs to be volatile
/**
* Defines the initial state
* @param initialState the given initial state
*/
public StepBoolean(final boolean initialState) {
- this.initialState = initialState ? TRUE : FALSE;
- state = this.initialState;
+ this.initialState = initialState ? 1 : 0;
+ this.state = this.initialState;
}
/**
@@ -49,19 +53,20 @@ public final class StepBoolean {
* @return the current state.
*/
public boolean get() {
- return state == TRUE;
+ return state == 1;
}
-
+
/**
* This changes the state of this step boolean function if it has not yet
changed.
* @return true if this call led to the change of the state; false if the
state has already been
* changed
*/
public boolean change() {
- final int notInitialState = initialState == TRUE ? FALSE : TRUE;
- return STATE_FIELD_UPDATER.compareAndSet(this, initialState,
notInitialState);
+ final int targetState = 1 - initialState;
+ // Transition 'state' from 'initialState' to 'targetState'
+ return STATE_HANDLE.compareAndSet(this, initialState, targetState);
}
-
+
/**
* Return true if the state has changed from the initial state
* @return true if the state has changed from the initial state
diff --git
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/Util.java
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/Util.java
index 7c4f947a..0c9f037e 100644
---
a/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/Util.java
+++
b/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/Util.java
@@ -370,7 +370,7 @@ public final class Util {
}
}
- public static void ensureReadOnly(Path path) {
+ public static void ensureReadOnly(final Path path) {
if (!Files.exists(path)) {
throw new IllegalArgumentException("File not found.");
}
@@ -384,44 +384,42 @@ public final class Util {
* @param resourceName the simple file name. No special characters or
slashes.
* @return a File System File
*/
- public static File getResourceFile(String resourceName) {
+ public static File getResourceFile(final String resourceName) {
Objects.requireNonNull(resourceName, "Given resourceName must not be
null");
if (resourceName.isEmpty()) { throw new IllegalArgumentException("Given
resourceName must not be empty"); }
// Normalize name: ClassLoaders MUST use forward slashes even on Windows
String normalizedName = resourceName.replace('\\', '/');
if (normalizedName.startsWith("/")) { normalizedName =
normalizedName.substring(1); }
- ClassLoader loader = Util.class.getClassLoader();
- URL url = loader.getResource(normalizedName);
+ final ClassLoader loader = Util.class.getClassLoader();
+ final URL url = loader.getResource(normalizedName);
if (url == null) { throw new IllegalArgumentException("Resource not found:
" + normalizedName); }
// If it's a real file, return it directly
if ("file".equals(url.getProtocol())) {
try {
- URI uri = url.toURI();
+ final URI uri = url.toURI();
return new File(uri); }
- catch (URISyntaxException e) { return new File(url.getPath()); }
+ catch (final URISyntaxException e) { return new File(url.getPath()); }
}
// If it's in a JAR, we must extract it for Memory.map() to work
// We use a prefix that won't collide with Windows reserved names
- File tempFile;
+ final File tempFile;
try { tempFile = File.createTempFile("datasketches-", ".bin"); }
- catch (IOException e1) { throw new IllegalArgumentException(e1); }
+ catch (final IOException e1) { throw new IllegalArgumentException(e1); }
tempFile.deleteOnExit();
try (InputStream in = loader.getResourceAsStream(normalizedName)) {
- if (in == null) throw new IllegalArgumentException("Could not open
stream for " + normalizedName);
+ if (in == null) { throw new IllegalArgumentException("Could not open
stream for " + normalizedName); }
// Use REPLACE_EXISTING to avoid "File Already Exists" errors on
Windows retries
Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- } catch (IOException e) { throw new IllegalArgumentException(e); }
+ } catch (final IOException e) { throw new IllegalArgumentException(e); }
// Final Windows Fix: Ensure the file is actually writable if you need to
setReadOnly later
//tempFile.setWritable(true);
return tempFile;
}
-
-
}
diff --git
a/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
b/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
index 2f91db52..e4304fde 100644
---
a/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
+++
b/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
@@ -37,7 +37,6 @@ public class ExampleMemoryRequestServerTest {
* This version is without a TWR block. All of the memory allocations are
done through the MemoryRequestServer
* and each is closed by the MemoryClient when it is done with them.
*/
- @SuppressWarnings("resource")
@Test
public void checkExampleMemoryRequestServer1() {
diff --git
a/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
b/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
deleted file mode 100644
index d7b40eac..00000000
---
a/datasketches-memory-java11/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
+++ /dev/null
@@ -1,62 +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.internal;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.testng.annotations.Test;
-
-public class MemoryCleanerTest {
-
- @Test
- public void cleanerDeallocates() {
- SimpleDeallocator deallocator = new SimpleDeallocator();
- MemoryCleaner cleaner = new MemoryCleaner(this, deallocator);
- cleaner.clean();
- assertTrue(SimpleDeallocator.getHasRun());
- }
-
- @Test
- public void noDeallocation() {
- SimpleDeallocator deallocator = new SimpleDeallocator();
- new MemoryCleaner(this, deallocator);
- assertFalse(SimpleDeallocator.getHasRun());
- }
-
- static final class SimpleDeallocator implements Runnable {
- static final AtomicBoolean hasRun = new AtomicBoolean();
-
- SimpleDeallocator() {
- hasRun.set(false);
- }
-
- @Override
- public void run() {
- hasRun.compareAndSet(false, true);
- }
-
- public static Boolean getHasRun() {
- return hasRun.get();
- }
- }
-}
diff --git a/datasketches-memory-java21/pom.xml
b/datasketches-memory-java21/pom.xml
index 3a0c799d..fbfb26da 100644
--- a/datasketches-memory-java21/pom.xml
+++ b/datasketches-memory-java21/pom.xml
@@ -45,20 +45,18 @@ under the License.
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.javadoc.skip>false</maven.javadoc.skip>
<maven.compiler.showWarnings>true</maven.compiler.showWarnings>
- <!-- jdk.internal.misc is used to call public Unsafe & public VM -->
-
<arg.jdk.internal.misc>--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED</arg.jdk.internal.misc>
- <!-- jdk.internal.ref is used to call public Cleaner -->
-
<arg.jdk.internal.ref>--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED</arg.jdk.internal.ref>
- <!-- sun.nio.ch.exports is used to open FileChannelImpl for DirectBuffer-->
-
<arg.sun.nio.ch.exports>--add-exports=java.base/sun.nio.ch=ALL-UNNAMED</arg.sun.nio.ch.exports>
- <!-- jdk.internal.access is used to access SharedSecrets and JavaNioAccess
-->
-
<arg.jdk.internal.access>--add-exports=java.base/jdk.internal.access=ALL-UNNAMED</arg.jdk.internal.access>
- <!-- java.nio is used to open MappedByteBuffer load0, isloaded0, & force0
for reflection -->
- <arg.java.nio>--add-opens=java.base/java.nio=ALL-UNNAMED</arg.java.nio>
- <!-- sun.nio.ch.opens is used to open FileChannelImpl for map0 & unmap0
for reflection-->
-
<arg.sun.nio.ch.opens>--add-opens=java.base/sun.nio.ch=ALL-UNNAMED</arg.sun.nio.ch.opens>
-
-
+ <!-- export.jdk.internal.misc is used to call public Unsafe & public VM -->
+
<export.jdk.internal.misc>--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED</export.jdk.internal.misc>
+ <!-- export.jdk.internal.ref is used to call public Cleaner -->
+
<export.jdk.internal.ref>--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED</export.jdk.internal.ref>
+ <!-- export.sun.nio.ch is used to open FileChannelImpl for DirectBuffer-->
+
<export.sun.nio.ch>--add-exports=java.base/sun.nio.ch=ALL-UNNAMED</export.sun.nio.ch>
+ <!-- export.jdk.internal.access is used to access SharedSecrets and
JavaNioAccess -->
+
<export.jdk.internal.access>--add-exports=java.base/jdk.internal.access=ALL-UNNAMED</export.jdk.internal.access>
+ <!-- open.java.nio is used to open MappedByteBuffer load0, isloaded0, &
force0 for reflection -->
+ <open.java.nio>--add-opens=java.base/java.nio=ALL-UNNAMED</open.java.nio>
+ <!-- open.sun.nio.ch is used to open FileChannelImpl for map0 & unmap0 for
reflection-->
+
<open.sun.nio.ch>--add-opens=java.base/sun.nio.ch=ALL-UNNAMED</open.sun.nio.ch>
</properties>
<dependencies>
@@ -100,12 +98,8 @@ under the License.
<configuration>
<fork>true</fork> <!-- required if Maven is using a different JVM -->
<compilerArgs>
- <arg>${arg.jdk.internal.misc}</arg>
- <arg>${arg.jdk.internal.ref}</arg>
- <arg>${arg.sun.nio.ch.exports}</arg>
- <arg>${arg.jdk.internal.access}</arg>
- <arg>${arg.java.nio}</arg>
- <arg>${arg.sun.nio.ch.opens}</arg>
+ <arg>${export.jdk.internal.misc}</arg>
+ <arg>${export.sun.nio.ch}</arg>
</compilerArgs>
</configuration>
</plugin>
@@ -122,12 +116,8 @@ under the License.
<argLine>
@{argLine}
@{jvm.args}
- ${arg.java.nio}
- ${arg.sun.nio.ch.exports}
- ${arg.sun.nio.ch.opens}
- ${arg.jdk.internal.misc}
- ${arg.jdk.internal.ref}
- ${arg.jdk.internal.access}
+ ${export.jdk.internal.misc}
+ ${export.sun.nio.ch}
-Dorg.slf4j.simpleLogger.log.org.testng=warn
</argLine>
<trimStackTrace>false</trimStackTrace>
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Memory.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Memory.java
index 366837ad..ef490910 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Memory.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Memory.java
@@ -66,7 +66,7 @@ public interface Memory extends Resource {
//Duplicates make no sense here
- //No Mapping in Java 21
+ //No Mapping in Java 17 or 21
//NO ALLOCATE OFF-HEAP, makes no sense
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Resource.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Resource.java
index 8b001287..4cb4281c 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Resource.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/Resource.java
@@ -135,31 +135,6 @@ public interface Resource extends AutoCloseable {
long thatOffsetBytes,
long lengthBytes);
- /**
- * Forces any changes made to the contents of this memory-mapped Resource to
be written to the storage
- * device described by the configured file descriptor.
- *
- * <p>If the file descriptor associated with this memory-mapped Resource
resides on a local storage device then when
- * this method returns, it is guaranteed that all changes made to this
mapped Resource since it was created, or since
- * this method was last invoked, will have been written to that device.</p>
- *
- * <p>If the file descriptor associated with this memory-mapped Resource
does not reside on a local device then no
- * such guarantee is made.</p>
- *
- * <p>If this memory-mapped Resource was not mapped in read/write mode
- * ({@link java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking
this method may have no effect.
- * In particular, this method has no effect for files mapped in read-only or
private
- * mapping modes. This method may or may not have an effect for
implementation-specific mapping modes.</p>
- *
- * @throws IllegalStateException if this Resource is not <em>alive</em>.
- * @throws IllegalStateException if this method is not accessed from the
owning thread.
- * @throws UnsupportedOperationException if this Resource is not
memory-mapped, e.g. if {@code isMapped() == false}.
- * @throws ReadOnlyException if this Resource is read-only.
- * @throws RuntimeException if there is some other error writing the
contents of this
- * memory-mapped Resource to the associated storage device.
- */
- void force();
-
/**
* Gets the capacity of this object in bytes
* @return the capacity of this object in bytes
@@ -240,27 +215,6 @@ public interface Resource extends AutoCloseable {
*/
boolean isHeap();
- /**
- * Tells whether or not the contents of this memory-mapped Resource is
resident in physical memory.
- *
- * <p>A return value of {@code true} implies that it is highly likely that
all of the data in this memory-mapped
- * Resource is resident in physical memory and may therefore be accessed
without incurring any virtual-memory page
- * faults or I/O operations.</p>
- *
- * <p>A return value of {@code false} does not necessarily imply that all of
the data in this memory-mapped Resource
- * is not resident in physical memory.</p>
- *
- * <p>The returned value is a hint, rather than a guarantee, because the
underlying operating system may have paged
- * out some of this Resource's data by the time that an invocation of this
method returns.</p>
- *
- * @return true if it is likely that all of the data in this memory-mapped
Resource is resident in physical memory
- *
- * @throws IllegalStateException if this Resource is not <em>alive</em>.
- * @throws IllegalStateException if this method is not accessed from the
owning thread.
- * @throws UnsupportedOperationException if this Resource is not
memory-mapped, e.g. if {@code isMapped() == false}.
- */
- boolean isLoaded();
-
/**
* If true, this is a <i>Memory</i> or <i>WritableMemory</i> instance, which
provides the Memory API.
* The Memory API is the principal API for this Memory Component.
@@ -319,19 +273,6 @@ public interface Resource extends AutoCloseable {
*/
boolean isAlive();
- /**
- * Loads the contents of this memory-mapped Resource into physical memory.
- *
- * <p>This method makes a best effort to ensure that, when it returns, this
contents of the memory-mapped Resource is
- * resident in physical memory. Invoking this method may cause some number
of page faults and
- * I/O operations to occur.</p>
- *
- * @throws IllegalStateException if this Resource is not <em>alive</em>.
- * @throws IllegalStateException if this method is not accessed from the
owning thread.
- * @throws UnsupportedOperationException if this Resource is not
memory-mapped, e.g. if {@code isMapped() == false}.
- */
- void load();
-
/**
* Returns a description of this object with an optional formatted hex
string of the data
* for the specified a range. Used primarily for testing.
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/WritableMemory.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/WritableMemory.java
index 1d9662bb..b2628aab 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/WritableMemory.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/WritableMemory.java
@@ -70,7 +70,7 @@ public interface WritableMemory extends Memory {
//Duplicates make no sense here
- //No Mapping in Java 21
+ //No Mapping in Java 17 or 21
//ALLOCATE OFF-HEAP
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
index 6db389c8..350678e4 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/AllocateDirect.java
@@ -21,82 +21,68 @@ package org.apache.datasketches.memory.internal;
import static org.apache.datasketches.memory.internal.UnsafeUtil.unsafe;
-import java.util.logging.Logger;
+import java.lang.ref.Cleaner;
/**
- * Provides access to direct (native) memory.
+ * Provides access to off-heap memory.
*
- * @author Roman Leventov
* @author Lee Rhodes
*/
-//@SuppressWarnings("restriction")
-final class AllocateDirect {
- static final Logger LOG =
Logger.getLogger(AllocateDirect.class.getCanonicalName());
-
+public class AllocateDirect {
+ private static final Cleaner CLEANER = Cleaner.create();
+ private final long rawAddress; //used for freeMemory
+ private final long alignedAddress; //data start address
private final Deallocator deallocator;
- private final long nativeBaseOffset;
- private final MemoryCleaner cleaner;
-
+ private final Cleaner.Cleanable cleanable;
+
/**
- * Base Constructor for allocate native memory.
- *
- * <p>Allocates and provides access to capacityBytes directly in native
(off-heap) memory
- * leveraging the MemoryImpl interface.
- * The allocated memory will be 8-byte aligned, but may not be page aligned.
- * @param capacityBytes the the requested capacity of off-heap memory.
Cannot be zero.
+ * Allocates off-heap memory with a default alignment of 8 bytes.
+ * @param capacityBytes must be greater than zero.
*/
AllocateDirect(final long capacityBytes) {
- final boolean pageAligned = VirtualMachineMemory.getIsPageAligned();
- final long pageSize = getPageSize();
- final long allocationSize = capacityBytes + (pageAligned ? pageSize : 0);
- final long nativeAddress;
+ this(capacityBytes, Long.BYTES);
+ }
+
+ /**
+ * Allocates off-heap memory with a specified alignment.
+ * @param capacityBytes must be greater than or equal 0.
+ * @param alignment the desired alignment. It must be a power of 2; e.g., 2,
4 or 8; and greater than 1.
+ */
+ AllocateDirect(final long capacityBytes, final int alignment) {
+ if (capacityBytes < 0) { throw new IllegalArgumentException("capacityBytes
must be >= 0: " + capacityBytes); }
+ final long mask = alignment - 1L;
+ if (checkAlignment(alignment)) {
+ throw new IllegalArgumentException("alignment must be a positive power
of 2 and greater than one: " + alignment); }
try {
- nativeAddress = unsafe.allocateMemory(allocationSize);
+ this.rawAddress = unsafe.allocateMemory(capacityBytes + mask);
} catch (final OutOfMemoryError err) {
throw new RuntimeException(err);
- }
- if (pageAligned && ((nativeAddress % pageSize) != 0)) {
- //Round up to page boundary
- nativeBaseOffset = (nativeAddress & ~(pageSize - 1L)) + pageSize;
- } else {
- nativeBaseOffset = nativeAddress;
- }
- deallocator = new Deallocator(nativeAddress);
- cleaner = new MemoryCleaner(this, deallocator);
+ }
+ this.alignedAddress = rawAddress & ~mask;
+ this.deallocator = new Deallocator(rawAddress);
+ this.cleanable = CLEANER.register(this, deallocator);
}
-
- public void close() {
- 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();
- }
- } finally {
- ResourceImpl.reachabilityFence(this);
- }
- }
-
- long getNativeBaseOffset() {
- return nativeBaseOffset;
+
+ public long getAddress() {
+ return alignedAddress;
}
- public static int getPageSize() {
- return unsafe.pageSize();
+ public void close() {
+ cleanable.clean();
}
public StepBoolean getValid() {
return deallocator.getValid();
}
+ //Must be static and NOT hold a reference to the outer AllocateDirect class
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 addressToFree;
private final StepBoolean valid = new StepBoolean(true); //only place for
this
- Deallocator(final long nativeAddress) {
- this.nativeAddress = nativeAddress;
+ Deallocator(final long addressToFree) {
+ this.addressToFree = addressToFree;
}
StepBoolean getValid() {
@@ -104,21 +90,20 @@ final class AllocateDirect {
}
@Override
- public void run() throws IllegalStateException {
- deallocate(true);
- }
-
- boolean deallocate(final boolean calledFromCleaner) throws
IllegalStateException {
- if (valid.change()) {
- if (calledFromCleaner) {
- // Warn about non-deterministic resource cleanup.
- LOG.warning("A direct resource was not closed explicitly.");
- }
- unsafe.freeMemory(nativeAddress);
- return true;
+ public void run() {
+ if (valid.change() && addressToFree != 0) {
+ unsafe.freeMemory(addressToFree);
}
- return false;
}
}
-
+
+ /**
+ * Returns true if given <i>n</i> is greater than one and a positive power
of 2.
+ *
+ * @param n The input argument.
+ * @return true if argument is greater than one and a positive power of 2.
+ */
+ private static final boolean checkAlignment(final int n) {
+ return (n > 1) && ((n & -n) == n);
+ }
}
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
index 5f174fca..d9c18975 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/BaseWritableMemoryImpl.java
@@ -121,9 +121,9 @@ public abstract class BaseWritableMemoryImpl extends
ResourceImpl implements Wri
final ByteOrder byteOrder, final MemoryRequestServer memReqSvr) {
Util.negativeCheck(capacityBytes, "capacityBytes");
Objects.requireNonNull(byteOrder, "byteOrder must be non-null.");
- final AllocateDirect direct = new AllocateDirect(capacityBytes);
+ final AllocateDirect direct = new AllocateDirect(capacityBytes, 3);
final int typeId = 0; //direct is never read-only on construction
- final long nativeBaseOffset = direct.getNativeBaseOffset();
+ final long nativeBaseOffset = direct.getAddress();
final long cumOffsetBytes = nativeBaseOffset;
final BaseWritableMemoryImpl wmem = Util.isNativeByteOrder(byteOrder)
? new DirectWritableMemoryImpl(
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
deleted file mode 100644
index fd21f119..00000000
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
+++ /dev/null
@@ -1,51 +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.internal;
-
-import jdk.internal.ref.Cleaner;
-
-/**
- * Extracts a version-dependent reference to the `jdk.internal.ref.Cleaner`
into
- * a standalone class. The package name for Cleaner has changed in
- * later versions. The appropriate class will be loaded by the class loader
- * depending on the Java version that is used.
- * For more information, see: https://openjdk.java.net/jeps/238
- */
-//@SuppressWarnings("restriction")
-public class MemoryCleaner {
- private final Cleaner cleaner;
-
- /**
- * Creates a new `jdk.internal.ref.Cleaner`.
- * @param referent the object to be cleaned
- * @param deallocator - the cleanup code to be run when the cleaner is
invoked.
- * return MemoryCleaner
- */
- public MemoryCleaner(final Object referent, final Runnable deallocator) {
- cleaner = Cleaner.create(referent, deallocator);
- }
-
- /**
- * Runs this cleaner, if it has not been run before.
- */
- public void clean() {
- cleaner.clean();
- }
-}
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
index 7f18658e..cccb0e75 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java
@@ -81,8 +81,6 @@ public abstract class ResourceImpl implements Resource {
static final String NOT_MAPPED_FILE_RESOURCE = "This is not a memory-mapped
file resource";
static final String THREAD_EXCEPTION_TEXT = "Attempted access outside owning
thread";
-
- //private static boolean JAVA_VERSION_WARNING_PRINTED = false;
static {
final String jdkVer = System.getProperty("java.version");
@@ -157,11 +155,6 @@ public abstract class ResourceImpl implements Resource {
if (!ok) { throw new IllegalArgumentException(
"Unsupported JDK Major Version. It must be one of 1.8, 8, 11, 17, 21,
25: " + jdkVer);
}
-// if (p0 > 11 && !JAVA_VERSION_WARNING_PRINTED) {
-// System.err.println(
-// "Warning: Java versions > Java 11 can only operate in restricted
mode where no off-heap operations are allowed!");
-// JAVA_VERSION_WARNING_PRINTED = true;
-// }
}
void checkNotReadOnly() {
@@ -239,10 +232,10 @@ public abstract class ResourceImpl implements Resource {
return CompareAndCopy.equals(this, thisOffsetBytes, (ResourceImpl) that,
thatOffsetBytes, lengthBytes);
}
- @Override
- public void force() { //overridden by Map Leaves
- throw new UnsupportedOperationException(NOT_MAPPED_FILE_RESOURCE);
- }
+// @Override
+// public void force() { //overridden by Map Leaves
+// throw new UnsupportedOperationException(NOT_MAPPED_FILE_RESOURCE);
+// }
//Overridden by ByteBuffer Leaves. Used internally and for tests.
ByteBuffer getByteBuffer() {
@@ -316,14 +309,9 @@ public abstract class ResourceImpl implements Resource {
return getUnsafeObject() != null;
}
- @Override
- public boolean isLoaded() { //overridden by Map Leaves
- throw new IllegalStateException(NOT_MAPPED_FILE_RESOURCE);
- }
-
@Override
public boolean isMapped() {
- return (getTypeId() & MAP) > 0;
+ return false;
}
@Override
@@ -370,11 +358,6 @@ public abstract class ResourceImpl implements Resource {
return true;
}
- @Override
- public void load() { //overridden by Map leaves
- throw new IllegalStateException(NOT_MAPPED_FILE_RESOURCE);
- }
-
private static String pad(final String s, final int fieldLen) {
return characterPad(s, fieldLen, ' ' , true);
}
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
index 45f81c35..e6f352de 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/StepBoolean.java
@@ -19,29 +19,33 @@
package org.apache.datasketches.memory.internal;
-import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
/**
- * This is a step boolean function that can change its state only once.
+ * This is a step boolean or latch function that can change its state only
once.
*
* @author Lee Rhodes
*/
public final class StepBoolean {
- private static final int FALSE = 0;
- private static final int TRUE = 1;
- private static final AtomicIntegerFieldUpdater<StepBoolean>
STATE_FIELD_UPDATER =
- AtomicIntegerFieldUpdater.newUpdater(StepBoolean.class, "state");
+ private static final VarHandle STATE_HANDLE;
+
+ static {
+ try {
+ STATE_HANDLE =
MethodHandles.lookup().findVarHandle(StepBoolean.class, "state", int.class);
+ } catch (final ReflectiveOperationException e) { throw new Error(e); }
+ }
private final int initialState;
- private volatile int state;
+ private volatile int state; // Still needs to be volatile
/**
* Defines the initial state
* @param initialState the given initial state
*/
public StepBoolean(final boolean initialState) {
- this.initialState = initialState ? TRUE : FALSE;
- state = this.initialState;
+ this.initialState = initialState ? 1 : 0;
+ this.state = this.initialState;
}
/**
@@ -49,19 +53,20 @@ public final class StepBoolean {
* @return the current state.
*/
public boolean get() {
- return state == TRUE;
+ return state == 1;
}
-
+
/**
* This changes the state of this step boolean function if it has not yet
changed.
* @return true if this call led to the change of the state; false if the
state has already been
* changed
*/
public boolean change() {
- final int notInitialState = initialState == TRUE ? FALSE : TRUE;
- return STATE_FIELD_UPDATER.compareAndSet(this, initialState,
notInitialState);
+ final int targetState = 1 - initialState;
+ // Transition 'state' from 'initialState' to 'targetState'
+ return STATE_HANDLE.compareAndSet(this, initialState, targetState);
}
-
+
/**
* Return true if the state has changed from the initial state
* @return true if the state has changed from the initial state
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/UnsafeUtil.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/UnsafeUtil.java
index 515d9f6f..fb2e48ee 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/UnsafeUtil.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/UnsafeUtil.java
@@ -86,11 +86,6 @@ public final class UnsafeUtil {
unsafeConstructor.setAccessible(true);
unsafe = unsafeConstructor.newInstance();
- // Alternative, but may not work across different JVMs.
- // Field field = Unsafe.class.getDeclaredField("theUnsafe");
- // field.setAccessible(true);
- // unsafe = (Unsafe) field.get(null);
-
} catch (final InstantiationException | IllegalAccessException |
IllegalArgumentException
| InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/Util.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/Util.java
index 7c4f947a..3cf917a1 100644
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/Util.java
+++
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/Util.java
@@ -21,18 +21,7 @@ package org.apache.datasketches.memory.internal;
import static java.util.Arrays.fill;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
import java.nio.ByteOrder;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.util.Objects;
import java.util.Random;
import org.apache.datasketches.memory.Memory;
@@ -306,122 +295,4 @@ public final class Util {
}
}
- /**
- * Checks if given value is null.
- * @param obj the given object
- * @param arg a meaningful name of the actual argument.
- * @throws IllegalArgumentException if value is null.
- */
- public static final void nullCheck(final Object obj, final String arg) {
- if (obj == null) {
- throw new IllegalArgumentException("The argument '" + arg + "' may not
be null.");
- }
- }
-
- //Resources NOTE: these 3 methods are duplicated in Java/ datasketches/Util
-
- /**
- * Gets the Path of the given resource file's shortName.
- *
- * <p>Note that the ClassLoader.getResource(shortName) returns a URL,
- * which can have special characters, e.g., "%20" for spaces. This method
- * obtains the URL, converts it to a URI, then does a uri.getPath(), which
- * decodes any special characters in the URI path. This is required to make
- * obtaining resources operating-system independent.</p>
- *
- * @param shortFileName the last name in the pathname's name sequence.
- * @return the absolute path of the given resource file's shortName.
- */
- public static String getResourcePath(final String shortFileName) {
- Objects.requireNonNull(shortFileName, "input parameter " + shortFileName +
" cannot be null.");
- try {
- final URL url = Util.class.getClassLoader().getResource(shortFileName);
- Objects.requireNonNull(url, "resource " + shortFileName + " could not be
acquired.");
- final URI uri = url.toURI();
- //decodes any special characters
- final String pathStr = uri.isAbsolute() ?
Paths.get(uri).toAbsolutePath().toString() : uri.getPath();
- return pathStr;
- } catch (final URISyntaxException e) {
- throw new IllegalArgumentException("Cannot find resource: " +
shortFileName + LS + e);
- }
- }
-
-// /**
-// * Gets the file defined by the given resource file's shortFileName.
-// * @param shortFileName the last name in the pathname's name sequence.
-// * @return the file defined by the given resource file's shortFileName.
-// */
-// public static File getResourceFile(final String shortFileName) {
-// return new File(getResourcePath(shortFileName));
-// }
-
- /**
- * Returns a byte array of the contents of the file defined by the given
resource file's
- * shortFileName.
- * @param shortFileName the last name in the pathname's name sequence.
- * @return a byte array of the contents of the file defined by the given
resource file's
- * shortFileName.
- */
- public static byte[] getResourceBytes(final String shortFileName) {
- try {
- return Files.readAllBytes(Paths.get(getResourcePath(shortFileName)));
- } catch (final IOException e) {
- throw new IllegalArgumentException("Cannot read resource: " +
shortFileName + LS + e);
- }
- }
-
- public static void ensureReadOnly(Path path) {
- if (!Files.exists(path)) {
- throw new IllegalArgumentException("File not found.");
- }
-
- // Works on Windows and POSIX)
- path.toFile().setReadOnly();
- }
-
- /**
- * Windows and JAR friendly get Resource File
- * @param resourceName the simple file name. No special characters or
slashes.
- * @return a File System File
- */
- public static File getResourceFile(String resourceName) {
- Objects.requireNonNull(resourceName, "Given resourceName must not be
null");
- if (resourceName.isEmpty()) { throw new IllegalArgumentException("Given
resourceName must not be empty"); }
- // Normalize name: ClassLoaders MUST use forward slashes even on Windows
- String normalizedName = resourceName.replace('\\', '/');
- if (normalizedName.startsWith("/")) { normalizedName =
normalizedName.substring(1); }
-
- ClassLoader loader = Util.class.getClassLoader();
- URL url = loader.getResource(normalizedName);
- if (url == null) { throw new IllegalArgumentException("Resource not found:
" + normalizedName); }
-
- // If it's a real file, return it directly
- if ("file".equals(url.getProtocol())) {
- try {
- URI uri = url.toURI();
- return new File(uri); }
- catch (URISyntaxException e) { return new File(url.getPath()); }
- }
-
- // If it's in a JAR, we must extract it for Memory.map() to work
- // We use a prefix that won't collide with Windows reserved names
- File tempFile;
- try { tempFile = File.createTempFile("datasketches-", ".bin"); }
- catch (IOException e1) { throw new IllegalArgumentException(e1); }
- tempFile.deleteOnExit();
-
- try (InputStream in = loader.getResourceAsStream(normalizedName)) {
- if (in == null) throw new IllegalArgumentException("Could not open
stream for " + normalizedName);
-
- // Use REPLACE_EXISTING to avoid "File Already Exists" errors on
Windows retries
- Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- } catch (IOException e) { throw new IllegalArgumentException(e); }
-
- // Final Windows Fix: Ensure the file is actually writable if you need to
setReadOnly later
- //tempFile.setWritable(true);
-
- return tempFile;
- }
-
-
}
diff --git
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/VirtualMachineMemory.java
b/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/VirtualMachineMemory.java
deleted file mode 100644
index 6056fd91..00000000
---
a/datasketches-memory-java21/src/main/java/org/apache/datasketches/memory/internal/VirtualMachineMemory.java
+++ /dev/null
@@ -1,56 +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.internal;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Extracts a version-dependent reference to the `jdk.internal.misc.VM` into a
standalone
- * class. The package name for VM has changed in later versions. The
appropriate
- * class will be loaded by the class loader depending on the Java version that
is used.
- * For more information, see: https://openjdk.java.net/jeps/238
- */
-public final class VirtualMachineMemory {
-
- private static final Class<?> VM_CLASS;
- private static final Method VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD;
- private static final boolean isPageAligned;
-
- static {
- try {
- VM_CLASS = Class.forName("jdk.internal.misc.VM");
- 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
- } catch (final ClassNotFoundException | NoSuchMethodException |
IllegalAccessException
- | IllegalArgumentException | InvocationTargetException |
SecurityException e) {
- throw new RuntimeException("Could not acquire jdk.internal.misc.VM: " +
e.getClass());
- }
- }
-
- /**
- * Returns true if the direct buffers should be page aligned.
- * @return flag that determines whether direct buffers should be page
aligned.
- */
- public static boolean getIsPageAligned() {
- return isPageAligned;
- }
-}
diff --git
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
index 2f91db52..e4304fde 100644
---
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
+++
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ExampleMemoryRequestServerTest.java
@@ -37,7 +37,6 @@ public class ExampleMemoryRequestServerTest {
* This version is without a TWR block. All of the memory allocations are
done through the MemoryRequestServer
* and each is closed by the MemoryClient when it is done with them.
*/
- @SuppressWarnings("resource")
@Test
public void checkExampleMemoryRequestServer1() {
diff --git
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
deleted file mode 100644
index d7b40eac..00000000
---
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
+++ /dev/null
@@ -1,62 +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.internal;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.testng.annotations.Test;
-
-public class MemoryCleanerTest {
-
- @Test
- public void cleanerDeallocates() {
- SimpleDeallocator deallocator = new SimpleDeallocator();
- MemoryCleaner cleaner = new MemoryCleaner(this, deallocator);
- cleaner.clean();
- assertTrue(SimpleDeallocator.getHasRun());
- }
-
- @Test
- public void noDeallocation() {
- SimpleDeallocator deallocator = new SimpleDeallocator();
- new MemoryCleaner(this, deallocator);
- assertFalse(SimpleDeallocator.getHasRun());
- }
-
- static final class SimpleDeallocator implements Runnable {
- static final AtomicBoolean hasRun = new AtomicBoolean();
-
- SimpleDeallocator() {
- hasRun.set(false);
- }
-
- @Override
- public void run() {
- hasRun.compareAndSet(false, true);
- }
-
- public static Boolean getHasRun() {
- return hasRun.get();
- }
- }
-}
diff --git
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryTest.java
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryTest.java
index aacdba4b..f3be613d 100644
---
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryTest.java
+++
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/MemoryTest.java
@@ -40,18 +40,12 @@ import org.apache.datasketches.memory.MemoryRequestServer;
import org.apache.datasketches.memory.Resource;
import org.apache.datasketches.memory.WritableBuffer;
import org.apache.datasketches.memory.WritableMemory;
-import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
public class MemoryTest {
private static final String LS = Util.LS;
- @BeforeClass
- public void setReadOnly() {
- UtilTest.setGettysburgAddressFileToReadOnly();
- }
-
@Test
public void checkDirectRoundTrip() throws Exception {
int n = 1024; //longs
diff --git
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/UtilTest.java
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/UtilTest.java
index 0bb9580e..890f5ac0 100644
---
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/UtilTest.java
+++
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/UtilTest.java
@@ -24,24 +24,13 @@
package org.apache.datasketches.memory.internal;
import static org.apache.datasketches.memory.internal.Util.characterPad;
-import static org.apache.datasketches.memory.internal.Util.getResourceBytes;
-import static org.apache.datasketches.memory.internal.Util.getResourceFile;
import static org.apache.datasketches.memory.internal.Util.negativeCheck;
-import static org.apache.datasketches.memory.internal.Util.nullCheck;
import static org.apache.datasketches.memory.internal.Util.zeroCheck;
import static org.apache.datasketches.memory.internal.Util.zeroPad;
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.IOException;
-import java.nio.file.Files;
-import java.nio.file.LinkOption;
-import java.nio.file.attribute.PosixFileAttributeView;
-import java.nio.file.attribute.PosixFileAttributes;
-import java.nio.file.attribute.PosixFilePermissions;
-
import org.apache.datasketches.memory.MemoryBoundsException;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
@@ -83,14 +72,7 @@ public class UtilTest {
}
@Test
- public void checkNullZeroNegativeChecks() {
- Object obj = null;
- try {
- nullCheck(obj, "Test Object");
- fail();
- } catch (IllegalArgumentException e) {
- //OK
- }
+ public void checkZeroNegativeChecks() {
try {
zeroCheck(0, "Test Long");
fail();
@@ -131,60 +113,6 @@ public class UtilTest {
}
}
- static final String getFileAttributes(File file) {
- try {
- PosixFileAttributes attrs = Files.getFileAttributeView(
- file.toPath(), PosixFileAttributeView.class, new
LinkOption[0]).readAttributes();
- String s = String.format("%s: %s %s %s%n",
- file.getPath(),
- attrs.owner().getName(),
- attrs.group().getName(),
- PosixFilePermissions.toString(attrs.permissions()));
- return s;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- static final void setGettysburgAddressFileToReadOnly() {
- File file = getResourceFile("GettysburgAddress.txt");
- try {
- Files.setPosixFilePermissions(file.toPath(),
PosixFilePermissions.fromString("r--r--r--"));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- //Resources
-
- @Test
- public void resourceFileExits() {
- final String shortFileName = "GettysburgAddress.txt";
- final File file = getResourceFile(shortFileName);
- assertTrue(file.exists());
- }
-
- @Test
- public void resourceFileNotFound() {
- final String shortFileName = "GettysburgAddress.txt";
- try { getResourceFile(shortFileName + "123"); }
- catch (IllegalArgumentException e) { //OK
- }
- }
-
- @Test
- public void resourceBytesCorrect() {
- final String shortFileName = "GettysburgAddress.txt";
- final byte[] bytes = getResourceBytes(shortFileName);
- assertTrue(bytes.length == 1541);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void resourceBytesFileNotFound() {
- final String shortFileName = "GettysburgAddress.txt";
- getResourceBytes(shortFileName + "123");
- }
-
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
diff --git
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ZeroCapacityTest.java
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ZeroCapacityTest.java
index fa500dbc..22b15fdf 100644
---
a/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ZeroCapacityTest.java
+++
b/datasketches-memory-java21/src/test/java/org/apache/datasketches/memory/internal/ZeroCapacityTest.java
@@ -28,7 +28,7 @@ import org.apache.datasketches.memory.WritableMemory;
import org.testng.annotations.Test;
/**
- * Although allocating zero bytes may be a bug, it is tolerated in Java.
+ * Although one might think that allocating zero bytes is a bug, it is
tolerated in Java.
*
* @author Lee Rhodes
*/
diff --git
a/datasketches-memory-java21/src/test/resources/GettysburgAddress.txt
b/datasketches-memory-java21/src/test/resources/GettysburgAddress.txt
deleted file mode 100644
index 3969d176..00000000
--- a/datasketches-memory-java21/src/test/resources/GettysburgAddress.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Abraham Lincoln's Gettysburg Address:
-
- Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to the proposition
that all men are created equal.
-
- Now we are engaged in a great civil war, testing whether that nation, or
any nation so conceived and so dedicated, can long endure. We are met on a
great battle-field of that war. We have come to dedicate a portion of that
field, as a final resting place for those who here gave their lives that that
nation might live. It is altogether fitting and proper that we should do this.
-
- But, in a larger sense, we can not dedicate —- we can not consecrate —- we
can not hallow —- this ground. The brave men, living and dead, who struggled
here, have consecrated it, far above our poor power to add or detract. The
world will little note, nor long remember what we say here, but it can never
forget what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far so nobly
advanced. It is rather for us [...]
diff --git a/tools/scripts/assets/CheckMemoryJar.java
b/tools/scripts/assets/CheckMemoryJar.java
index ba16ca42..cbc46c98 100644
--- a/tools/scripts/assets/CheckMemoryJar.java
+++ b/tools/scripts/assets/CheckMemoryJar.java
@@ -28,12 +28,13 @@ import org.apache.datasketches.memory.WritableMemory;
public class CheckMemoryJar {
- public void printJDK() {
+ public int printJDK() {
String JdkVersionString = System.getProperty("java.version");
int JdkMajorVersion = getJavaMajorVersion(JdkVersionString);
println("JDK Full Version : " + JdkVersionString);
println("JDK Major Version: " + JdkMajorVersion);
println("");
+ return JdkMajroVersion;
}
public void checkHeapWritableMemory() {
@@ -69,6 +70,7 @@ public class CheckMemoryJar {
}
}
+ //MAP
public void checkMap(String mappedFilePath) throws Exception {
try {
String str = "4 - Memory Map Successful";
@@ -82,18 +84,21 @@ public class CheckMemoryJar {
}
public static void main(final String[] args) throws Exception {
- if (args.length < 1) {
+ CheckMemoryJar check = new CheckMemoryJar();
+ int majVer = check.printJDK();
+
+ if (majVer <= 11) {
+ if (args.length < 1) {
System.out.println("Please provide the full path to the memory
mapped file!");
System.exit(1);
+ }
+ String mappedFilePath = args[0];
+ check.checkMap(mappedFilePath);
}
-
- String mappedFilePath = args[0];
- CheckMemoryJar check = new CheckMemoryJar();
- check.printJDK();
+ //all versions
check.checkHeapWritableMemory();
check.checkAllocateDirect();
check.checkByteBuffer();
- check.checkMap(mappedFilePath);
println("");
println("All checks passed.");
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]