我正在开发一个Java API,其中许多Java对象实际上是等效C++对象的包装器.Java对象创建C++对象,并在不再需要它们时负责释放它们.我想知道最好的模式,我可以看到两个可能的选择:
使用静态本机方法调用和最终变量构造构造函数中的C++对象以保存本机句柄.
public abstract class NativeBackedObject1 implements java.lang.AutoCloseable {
protected final long _nativeHandle;
protected final AtomicBoolean _nativeOwner;
protected NativeBackedObject1(final long nativeHandle) {
this._nativeHandle = nativeHandle;
this._nativeOwner = new AtomicBoolean(true);
}
@Override
public close() {
if(_nativeOwner.copareAndSet(true, false)) {
disposeInternal();
}
}
protected abstract void disposeInternal();
}
public SomeFoo1 extends NativeBackendObject1 {
public SomeFoo1() {
super(newFoo());
}
@Override
protected final void disposeInternal() {
//TODO: any local object specific cleanup
disposeInternal(_nativeHandle);
}
private native static long newFoo();
private native disposeInternal(final long nativeHandle); …Run Code Online (Sandbox Code Playgroud)