View Javadoc
1   /*
2    * Copyright 2025 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import io.netty.util.internal.logging.InternalLogger;
19  import io.netty.util.internal.logging.InternalLoggerFactory;
20  
21  import java.lang.foreign.Arena;
22  import java.lang.foreign.MemorySegment;
23  import java.nio.ByteBuffer;
24  
25  /**
26   * Provide a way to clean direct {@link ByteBuffer} instances on Java 24+,
27   * where we don't have {@code Unsafe} available, but we have memory segments.
28   * <p>
29   * The FFM API is compiled against the {@code netty-ffm-stub} module, and only used from the nested {@link Arenas}
30   * class, which is only loaded on Java versions that have the FFM API.
31   */
32  final class CleanerJava25 implements Cleaner {
33      private static final InternalLogger logger;
34  
35      private static final boolean SUPPORTED;
36  
37      static {
38          boolean suitableJavaVersion;
39          if (System.getProperty("org.graalvm.nativeimage.imagecode") != null) {
40              // native image supports this since 25, but we don't use PlatformDependent0 here, since
41              // we need to initialize CleanerJava25 at build time.
42              String v = System.getProperty("java.specification.version");
43              try {
44                  suitableJavaVersion = Integer.parseInt(v) >= 25;
45              } catch (NumberFormatException e) {
46                  suitableJavaVersion = false;
47              }
48              // also need to prevent initializing the logger at build time
49              logger = null;
50          } else {
51              // Only attempt to use MemorySegments on Java 25 or greater, because of the following JDK bugs:
52              // - https://bugs.openjdk.org/browse/JDK-8357145
53              // - https://bugs.openjdk.org/browse/JDK-8357268
54              suitableJavaVersion = PlatformDependent0.javaVersion() >= 25;
55              logger = InternalLoggerFactory.getInstance(CleanerJava25.class);
56          }
57  
58          Throwable error;
59          if (suitableJavaVersion) {
60              try {
61                  Arenas.checkShared();
62                  error = null;
63              } catch (Throwable throwable) {
64                  error = throwable;
65              }
66          } else {
67              error = new UnsupportedOperationException("java.lang.foreign.MemorySegment unavailable");
68          }
69          if (logger != null) {
70              if (error == null) {
71                  logger.debug("java.nio.ByteBuffer.cleaner(): available");
72              } else {
73                  logger.debug("java.nio.ByteBuffer.cleaner(): unavailable", error);
74              }
75          }
76          SUPPORTED = error == null;
77      }
78  
79      static boolean isSupported() {
80          return SUPPORTED;
81      }
82  
83      @Override
84      public CleanableDirectBuffer allocate(int capacity) {
85          PlatformDependent.incrementMemoryCounter(capacity);
86          try {
87              return Arenas.allocate(capacity);
88          } catch (RuntimeException e) {
89              PlatformDependent.decrementMemoryCounter(capacity);
90              throw e; // Propagate the runtime exceptions that the Arena would normally throw.
91          } catch (Throwable e) {
92              PlatformDependent.decrementMemoryCounter(capacity);
93              throw new IllegalStateException("Unexpected allocation exception", e);
94          }
95      }
96  
97      @Override
98      public void freeDirectBuffer(ByteBuffer buffer) {
99          throw new UnsupportedOperationException("Cannot clean arbitrary ByteBuffer instances");
100     }
101 
102     @Override
103     public boolean hasExpensiveClean() {
104         // Closing shared arenas can be fairly expensive if we do it a lot,
105         // because it relies on inter-thread handshakes.
106         return true;
107     }
108 
109     private static final class Arenas {
110         static void checkShared() {
111             // Try to access shared Arena which might fail on GraalVM 25.0.0 if not enabled
112             // See https://github.com/netty/netty/issues/15762
113             Arena.ofShared().close();
114         }
115 
116         static CleanableDirectBufferImpl allocate(int capacity) {
117             // Each buffer gets its own shared arena, which is closed to free the memory.
118             Arena arena = Arena.ofShared();
119             MemorySegment segment = arena.allocate(capacity);
120             return new CleanableDirectBufferImpl(arena, segment.asByteBuffer(), segment.address());
121         }
122     }
123 
124     private static final class CleanableDirectBufferImpl implements CleanableDirectBuffer {
125         private final AutoCloseable closeable;
126         private final ByteBuffer buffer;
127         private final long memoryAddress;
128 
129         CleanableDirectBufferImpl(AutoCloseable closeable, ByteBuffer buffer, long memoryAddress) {
130             this.closeable = closeable;
131             this.buffer = buffer;
132             this.memoryAddress = memoryAddress;
133         }
134 
135         @Override
136         public ByteBuffer buffer() {
137             return buffer;
138         }
139 
140         @Override
141         public void clean() {
142             int capacity = buffer.capacity();
143             try {
144                 closeable.close();
145             } catch (RuntimeException e) {
146                 throw e; // Propagate the runtime exceptions that Arena would normally throw.
147             } catch (Exception e) {
148                 throw new IllegalStateException("Unexpected close exception", e);
149             } finally {
150                 PlatformDependent.decrementMemoryCounter(capacity);
151             }
152         }
153 
154         @Override
155         public boolean hasMemoryAddress() {
156             return true;
157         }
158 
159         @Override
160         public long memoryAddress() {
161             return memoryAddress;
162         }
163     }
164 }