Class NativeHandle

java.lang.Object
io.github.fherbreteau.vodozemac.NativeHandle
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
Account, Ecies, Ed25519KeyPair, EstablishedEcies, EstablishedSas, InboundGroupSession, OlmSession, OutboundGroupSession, PkDecryption, PkEncryption, Sas

public abstract class NativeHandle extends Object implements AutoCloseable
Abstract base class for all objects backed by a native handle (raw pointer).

Each subclass holds a native pointer to a Rust object allocated on the heap. The pointer is released when close() is called, which delegates to the subclass-specific native free function supplied to the constructor.

This class implements AutoCloseable and should be used in a try-with-resources block to ensure native resources are properly released. The close() method is idempotent — calling it more than once has no effect. Any method that accesses the native pointer after close() has been called will throw an IllegalStateException.

As a best-effort safety net, an instance that becomes garbage without having been closed is cleaned up by a Cleaner: its native memory is released and a warning is logged. The safety net is not deterministic and should never be relied upon — always close handles explicitly.

Instances are safe to use from multiple threads: every method that accesses the native handle is synchronized on the instance, so native calls on the same object are serialized and close() can never race with an ongoing native call. Constructors and static factory methods that only create fresh native objects require no synchronization.

Author:
François HERBRETEAU
  • Constructor Details

    • NativeHandle

      protected NativeHandle(long ptr, LongConsumer nativeFreer)
  • Method Details

    • nativePtr

      protected final long nativePtr()
    • checkNotClosed

      protected final void checkNotClosed()
    • close

      public final void close()
      Closes this resource by releasing its associated native resources.

      This method is idempotent: calling it more than once has no effect.

      Specified by:
      close in interface AutoCloseable
    • invalidate

      protected final void invalidate()
      Invalidates this handle without releasing its native resources, because ownership of the native object has been transferred elsewhere.

      Subclasses whose native methods consume the native object and hand its ownership to a new Java object (e.g. a Sas consumed by diffieHellman) must call this method instead of dropping the pointer themselves, so that the Cleaner safety net does not release the already-transferred pointer a second time. After this call the handle behaves as if it had been closed.