View Javadoc

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.util.concurrent.atomic.AtomicIntegerFieldUpdater;
19  import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
20  
21  final class AtomicFieldUpdaterUtil {
22  
23      private static final boolean AVAILABLE;
24  
25      static final class Node {
26          volatile Node next;
27          Node() {
28              super();
29          }
30      }
31  
32      static {
33          boolean available = false;
34          try {
35              AtomicReferenceFieldUpdater<Node, Node> tmp =
36                  AtomicReferenceFieldUpdater.newUpdater(
37                          Node.class, Node.class, "next");
38  
39              // Test if AtomicReferenceFieldUpdater is really working.
40              Node testNode = new Node();
41              tmp.set(testNode, testNode);
42              if (testNode.next != testNode) {
43                  // Not set as expected - fall back to the safe mode.
44                  throw new Exception();
45              }
46              available = true;
47          } catch (Throwable t) {
48              // Running in a restricted environment with a security manager.
49          }
50          AVAILABLE = available;
51      }
52  
53      static <T, V> AtomicReferenceFieldUpdater<T, V> newRefUpdater(Class<T> tclass, Class<V> vclass, String fieldName) {
54          if (AVAILABLE) {
55              return AtomicReferenceFieldUpdater.newUpdater(tclass, vclass, fieldName);
56          } else {
57              return null;
58          }
59      }
60  
61      static <T> AtomicIntegerFieldUpdater<T> newIntUpdater(Class<T> tclass, String fieldName) {
62          if (AVAILABLE) {
63              return AtomicIntegerFieldUpdater.newUpdater(tclass, fieldName);
64          } else {
65              return null;
66          }
67      }
68  
69      static boolean isAvailable() {
70          return AVAILABLE;
71      }
72  
73      private AtomicFieldUpdaterUtil() {
74          // Unused
75      }
76  }