class Peer { // used to hold the C++ object pointer private long peerobj; // create native object private native long create(int i); // destroy native object private native synchronized void destroy(long p); // get value of native object private native int getvalue(long p); // constructor - call create() to create native object public Peer(int i) { peerobj = create(i); System.out.println("create peerobj = " + peerobj); } // destroy native object if not already done public synchronized void destroy() { if (peerobj != 0) { System.out.println("destroy peerobj = " + peerobj); destroy(peerobj); peerobj = 0; } } // get value from native object public int getValue() { if (peerobj == 0) { throw new IllegalStateException( "getValue called on destroyed object"); } return getvalue(peerobj); } // destroy native object if it's still around // when finalize called from garbage collection public void finalize() { destroy(); } }