자바 JNA(5)-메모리 대상 이 할당 한 메모리 방출

7405 단어 Java
자바 프로 세 스 의 메모 리 는Java NonHeap ,Java Heap ,Native Heap 를 포함한다.JNA 의 메모리 대상 은 네 이 티 브 힙 에서 공간 을 배분 하 는 것 이다.그러나 자바 의 GC 는 자바 힙 공간 을 대상 으로 설계 되 었 으 며 자바 힙 공간 이 부족 할 때 GC 를 촉발 하지만 네 이 티 브 힙 공간 이 부족 하면 GC 를 촉발 하지 않 습 니 다.따라서 자바 힙 이 공간 을 많이 차지 하지 않 을 때 GC 가 메모리 대상 을 떨 어 뜨리 지 않 고 finalize()방법 을 실행 하여 분 배 된 네 이 티 브 힙 공간 을 방출 하지 않 는 다.참고:http://ayufox.iteye.com/blog/723896
메모리 의 finalize()방법:
 /** Properly dispose of native memory when this object is GC'd. */
    @Override
    protected void finalize() {
        dispose();
    }
 
    /** Free the native memory and set peer to zero */
    protected synchronized void dispose() {
        try {
            free(peer);
        } finally {
            peer = 0;
            allocatedMemory.remove(this);
        }
    }
 
 protected static void free(long p) {
        // free(0) is a no-op, so avoid the overhead of the call
        if (p != 0) {
            Native.free(p);
        }
    }

그 중에서 Native.free()방법 은 다음 과 같다.
    /**
     * Call the real native free
     * @param ptr native address to be freed; a value of zero has no effect,
     * passing an already-freed pointer will cause pain.
     */
    public static native void free(long ptr);

Pointer 클래스 의 방법:
 	/** Read the native peer value.  Use with caution. */
    public static long nativeValue(Pointer p) {
        return p == null ? 0 : p.peer;
    }
 
    /** Set the native peer value.  Use with caution. */
    public static void nativeValue(Pointer p, long value) {
        p.peer = value;
    }

위의 소스 코드 를 통 해 알 수 있 듯 이 메모리 가 GC 에 떨 어 지면 분 배 된 직접 메모 리 를 자동 으로 방출 합 니 다(전 제 는 GC 를 실행 하 는 것 입 니 다).메모리 로 직접 메모 리 를 너무 많이 분배 하여 직접 메모리 공간 이 부족 하지 않도록 메모리 로 분 배 된 메모 리 를 수 동 으로 방출 할 수 있 습 니 다.방법 은 다음 과 같 습 니 다.
Pointer p = new Memory(1024 * 1024);
long peer = Pointer.nativeValue(p);
Native.free(peer);//      
Pointer.nativeValue(p, 0);//  Memory   GC     Nativ.free()  

마지막 줄 코드 를 호출 하지 않 으 면
Pointer.nativeValue(p, 0);

GC 에 서 는 오류 가 발생 하고 프로그램 이 비정상적 으로 종 료 됩 니 다.

좋은 웹페이지 즐겨찾기