I don't know of any garbage-collected language that interoperates well
with reference-counted and manually-managed memory. In my opinion,
the best option is to wrap pointers to native resources in a class
like this:
public class Foo implements AutoCloseable {
private long peer;
public Foo() {
this.peer = createFoo();
}
public synchronized void doSomething() {
if (peer == 0) {
throw new IllegalStateException("already closed");
}
nativeDoSomething(peer);
}
public synchronized void close() {
try {
releaseFoo(peer);
} finally {
peer = 0;
}
}
private static native long createFoo();
private static native void nativeDoSomething(long peer);
private static native void releaseFoo(long peer); // decrement ref
count or whatever is appropriate
}
That allows you to safely release the resource when you're done using
it and avoid dangling pointers. You can use try-with-resources to
ensure a resource with a scoped lifetime is always released. If the
lifetime is more complicated, you have to explicitly call `close` when
the resource is no longer needed. That's how the RocksDB Java
bindings work:
https://github.com/facebook/rocksdb/wiki/RocksJava-Basics#memory-management.
A similar strategy is used for other resources in Java like network
sockets, etc. which need to be managed independently of garbage
collected memory.
It's annoying to have to manually manage resources like this, but it's
the only efficient way to do it in a language like Java. Rust and C++
have smart pointers which make this quite a bit easier, and that's one
of the reasons I prefer Rust over Java these days.
> --
> You received this message because you are subscribed to the Google Groups
> "Avian" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to
avian+un...@googlegroups.com.
> To post to this group, send email to
av...@googlegroups.com.
> Visit this group at
https://groups.google.com/group/avian.
> For more options, visit
https://groups.google.com/d/optout.