package com.litl.leveldb;

import java.io.Closeable;

import android.util.Log;

abstract class NativeObject implements Closeable {
    private static final String TAG = NativeObject.class.getSimpleName();
    protected long mPtr;
    private int mRefCount = 0;

    protected NativeObject() {
        // The Java wrapper counts as one reference, will
        // be released when closed
        ref();
    }

    protected NativeObject(long ptr) {
        this();

        if (ptr == 0) {
            throw new OutOfMemoryError("Failed to allocate native object");
        }

        mPtr = ptr;
    }

    synchronized protected long getPtr() {
        return mPtr;
    }

    protected void assertOpen(String message) {
        if (getPtr() == 0) {
            throw new IllegalStateException(message);
        }
    }

    synchronized void ref() {
        mRefCount++;
    }

    synchronized void unref() {
        if (mRefCount <= 0) {
            throw new IllegalStateException("Reference count is already 0");
        }

        mRefCount--;

        if (mRefCount == 0) {
            closeNativeObject(mPtr);
            mPtr = 0;
        }
    }

    protected abstract void closeNativeObject(long ptr);

    @Override
    public void close() {
        unref();
    }

    @Override
    protected void finalize() throws Throwable {
        if (mPtr != 0) {
            Log.w(TAG,
                    "NativeObject "
                            + getClass().getSimpleName()
                            + " was finalized before native resource was closed, did you forget to call close()?");
        }

        super.finalize();
    }
}

@@ -47,16 +47,47 @@
 eable;%0A%0A
+import android.text.TextUtils;%0A
 import a
@@ -1407,95 +1407,207 @@
     
-Log.w(TAG,%0A                    %22NativeObject %22%0A                            + getClass()
+Class%3C?%3E clazz = getClass();%0A            String name = clazz.getSimpleName();%0A            while (TextUtils.isEmpty(name)) %7B%0A                clazz = clazz.getSuperclass();%0A                name = clazz
 .get
@@ -1618,16 +1618,17 @@
 leName()
+;
 %0A       
@@ -1620,32 +1620,175 @@
 Name();%0A        
+    %7D%0A%0A            Log.w(TAG, %22NativeObject %22 + name + %22 refcount: %22 + mRefCount%0A                    + %22 id: %22 + System.identityHashCode(this)%0A
                 

Improve leaked resource logging messages