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