回收DirectByteBuffer

爲避免GC的負效應, 使用DirectByteBuffer管理原始(Raw)數據會爲高負載的系統帶來性能的提高. DirectByteBuffer默認是由GC來回收的, 這一般可以知足需求, 若要想本身控制回收的時機, 可使用這段代碼.java

 

import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * {@link DirectByteBufferCleaner}
 *
 * @author zhongl
 * @created 2011-1-14
 */
public final class DirectByteBufferCleaner {
  private DirectByteBufferCleaner() {}

  public static void clean(final ByteBuffer byteBuffer) {
    if (!byteBuffer.isDirect()) return;
    try {
      Object cleaner = invoke(byteBuffer, "cleaner");
      invoke(cleaner, "clean");
    } catch (Exception e) { /* ignore */ }
  }

  private static Object invoke(final Object target, String methodName) throws Exception {
    final Method method = target.getClass().getMethod(methodName);
    return AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { try { return method.invoke(target); } catch (Exception e) { throw new RuntimeException(e); } } }); } }
 

已有 0 人發表留言,猛擊->>這裏<<-參與討論


JavaEye推薦
相關文章
相關標籤/搜索