1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.security.AccessController;
19 import java.security.PrivilegedActionException;
20 import java.security.PrivilegedExceptionAction;
21 import java.util.Queue;
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.atomic.AtomicInteger;
24
25
26
27
28
29
30
31
32
33
34
35 public final class DetectionUtil {
36
37 private static final int JAVA_VERSION = javaVersion0();
38 private static final boolean HAS_UNSAFE = hasUnsafe(AtomicInteger.class.getClassLoader());
39 private static final boolean IS_WINDOWS;
40 static {
41 String os = SystemPropertyUtil.get("os.name", "").toLowerCase();
42
43 IS_WINDOWS = os.contains("win");
44 }
45
46
47
48
49
50 public static boolean isWindows() {
51 return IS_WINDOWS;
52 }
53
54 public static boolean hasUnsafe() {
55 return HAS_UNSAFE;
56 }
57
58 public static int javaVersion() {
59 return JAVA_VERSION;
60 }
61
62 private static boolean hasUnsafe(ClassLoader loader) {
63 boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
64 if (noUnsafe) {
65 return false;
66 }
67
68
69 boolean tryUnsafe;
70 if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
71 tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
72 } else {
73 tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
74 }
75
76 if (!tryUnsafe) {
77 return false;
78 }
79
80 try {
81 Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
82 return hasUnsafeField(unsafeClazz);
83 } catch (Exception e) {
84
85 }
86
87 return false;
88 }
89
90 private static boolean hasUnsafeField(final Class<?> unsafeClass) throws PrivilegedActionException {
91 return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
92 public Boolean run() throws Exception {
93 unsafeClass.getDeclaredField("theUnsafe");
94 return true;
95 }
96 });
97 }
98
99 private static int javaVersion0() {
100 try {
101
102
103
104 Class.forName("android.app.Application");
105 return 6;
106 } catch (ClassNotFoundException e) {
107
108 }
109
110 try {
111 Class.forName(
112 "java.util.concurrent.LinkedTransferQueue", false,
113 BlockingQueue.class.getClassLoader());
114 return 7;
115 } catch (Exception e) {
116
117 }
118
119 try {
120 Class.forName(
121 "java.util.ArrayDeque", false, Queue.class.getClassLoader());
122 return 6;
123 } catch (Exception e) {
124
125 }
126
127 return 5;
128 }
129
130 private DetectionUtil() {
131
132 }
133 }