1 /*
2 * Copyright 2012 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package org.jboss.netty.util.internal;
17
18 import java.lang.reflect.Method;
19 import java.nio.ByteBuffer;
20
21 /**
22 * This is fork of ElasticSearch's ByteBufferAllocator.Cleaner class
23 */
24 public final class ByteBufferUtil {
25 private static final boolean CLEAN_SUPPORTED;
26 private static final Method directBufferCleaner;
27 private static final Method directBufferCleanerClean;
28
29 static {
30 Method directBufferCleanerX = null;
31 Method directBufferCleanerCleanX = null;
32 boolean v;
33 try {
34 directBufferCleanerX = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner");
35 directBufferCleanerX.setAccessible(true);
36 directBufferCleanerCleanX = Class.forName("sun.misc.Cleaner").getMethod("clean");
37 directBufferCleanerCleanX.setAccessible(true);
38 v = true;
39 } catch (Exception e) {
40 v = false;
41 }
42 CLEAN_SUPPORTED = v;
43 directBufferCleaner = directBufferCleanerX;
44 directBufferCleanerClean = directBufferCleanerCleanX;
45 }
46
47 /**
48 * Destroy the given {@link ByteBuffer} if possible
49 */
50 public static void destroy(ByteBuffer buffer) {
51 if (CLEAN_SUPPORTED && buffer.isDirect()) {
52 try {
53 Object cleaner = directBufferCleaner.invoke(buffer);
54 directBufferCleanerClean.invoke(cleaner);
55 } catch (Exception e) {
56 // silently ignore exception
57 }
58 }
59 }
60
61 private ByteBufferUtil() {
62 // Utility class
63 }
64 }