View Javadoc
1   /*
2    * Copyright 2014 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 io.netty.util.internal;
17  
18  import sun.misc.Unsafe;
19  
20  import java.lang.reflect.Field;
21  import java.lang.reflect.Modifier;
22  import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
23  
24  final class UnsafeAtomicReferenceFieldUpdater<U, M> extends AtomicReferenceFieldUpdater<U, M> {
25      private final long offset;
26      private final Unsafe unsafe;
27  
28      UnsafeAtomicReferenceFieldUpdater(Unsafe unsafe, Class<U> tClass, String fieldName) throws NoSuchFieldException {
29          Field field = tClass.getDeclaredField(fieldName);
30          if (!Modifier.isVolatile(field.getModifiers())) {
31              throw new IllegalArgumentException("Must be volatile");
32          }
33          this.unsafe = unsafe;
34          offset = unsafe.objectFieldOffset(field);
35      }
36  
37      @Override
38      public boolean compareAndSet(U obj, M expect, M update) {
39          return unsafe.compareAndSwapObject(obj, offset, expect, update);
40      }
41  
42      @Override
43      public boolean weakCompareAndSet(U obj, M expect, M update) {
44          return unsafe.compareAndSwapObject(obj, offset, expect, update);
45      }
46  
47      @Override
48      public void set(U obj, M newValue) {
49          unsafe.putObjectVolatile(obj, offset, newValue);
50      }
51  
52      @Override
53      public void lazySet(U obj, M newValue) {
54          unsafe.putOrderedObject(obj, offset, newValue);
55      }
56  
57      @SuppressWarnings("unchecked")
58      @Override
59      public M get(U obj) {
60          return (M) unsafe.getObjectVolatile(obj, offset);
61      }
62  }