16 Mart 2021 Salı

MemorySegment Arayüzü

Giriş
Açıklaması şöyle
Foreign-memory Access API is a JEP 383 implementation to allow programs to efficiently access foreign memory outside the allocated Java Heap. It was first introduced in Java 14 as a preview and now the improved version is released as part of Java 15. This API allows allocating native memory segment quickly ...
Açıklaması şöyle. Yani ByteBuffer.allocateDirect() bazı kısıtlamalarla geliyor.
Before the introduction of the foreign memory access API in Java, there were two main ways to access native memory in Java. These are java.nio.ByteBuffer and sun.misc.Unsafe classes.

Let's have a quick look at the advantages and disadvantages of these APIs.

2.1. ByteBuffer API
The ByteBuffer API allows the creation of direct, off-heap byte buffers. These buffers can be directly accessed from a Java program. However, there are some limitations:

- The buffer size can't be more than two gigabytes
- The garbage collector is responsible for memory deallocation

Furthermore, incorrect use of a ByteBuffer can cause a memory leak and OutOfMemory errors. This is because an unused memory reference can prevent the garbage collector from deallocating the memory.

2.2. Unsafe API
The Unsafe API is extremely efficient due to its addressing model. However, as the name suggests, this API is unsafe and has several drawbacks:

- It often allows the Java programs to crash the JVM due to illegal memory usage
- It's a non-standard Java API

allocateNative metodu
Örnek
Şöyle yaparız
MemorySegment.allocateNative(100);

Hiç yorum yok:

Yorum Gönder