package com.litl.leveldb;

import java.io.Closeable;
import java.util.concurrent.atomic.AtomicInteger;

import android.util.Log;

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

    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;
    }

    protected long getPtr() {
        return mPtr;
    }

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

    void ref() {
        mRefCount.incrementAndGet();
    }

    void unref() {
        if (mRefCount.decrementAndGet() == 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();
    }
}

@@ -49,58 +49,8 @@
 ble;
-%0Aimport java.util.concurrent.atomic.AtomicInteger;
 %0A%0Aim
@@ -239,53 +239,25 @@
 ate 
-AtomicInteger mRefCount = new AtomicInteger()
+int mRefCount = 0
 ;%0A%0A 
@@ -591,32 +591,45 @@
 ptr;%0A    %7D%0A%0A    
+synchronized 
 protected long g
@@ -726,20 +726,24 @@
     if (
-m
+get
 Ptr
+()
  == 0) %7B
@@ -814,24 +814,37 @@
 %0A    %7D%0A%0A    
+synchronized 
 void ref() %7B
@@ -865,38 +865,35 @@
 ount
-.incrementAndGet();%0A    %7D%0A%0A   
+++;%0A    %7D%0A%0A    synchronized
  voi
@@ -929,26 +929,148 @@
 ount
-.decrementAndGet()
+ %3C= 0) %7B%0A            throw new IllegalStateException(%22Reference count is already 0%22);%0A        %7D%0A%0A        mRefCount--;%0A%0A        if (mRefCount
  == 

Add additional checks in unref()