Skip to content

Instantly share code, notes, and snippets.

@Arbow
Created July 19, 2012 03:22
Show Gist options
  • Save Arbow/3140545 to your computer and use it in GitHub Desktop.
Save Arbow/3140545 to your computer and use it in GitHub Desktop.
回收DirectByteBuffer
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
* @from http://my.oschina.net/zhongl/blog/13880
*/
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);
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment