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.AtomicIntegerFieldUpdater;
23  
24  final class UnsafeAtomicIntegerFieldUpdater<T> extends AtomicIntegerFieldUpdater<T> {
25      private final long offset;
26      private final Unsafe unsafe;
27  
28      UnsafeAtomicIntegerFieldUpdater(Unsafe unsafe, Class<?> 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(T obj, int expect, int update) {
39          return unsafe.compareAndSwapInt(obj, offset, expect, update);
40      }
41  
42      @Override
43      public boolean weakCompareAndSet(T obj, int expect, int update) {
44          return unsafe.compareAndSwapInt(obj, offset, expect, update);
45      }
46  
47      @Override
48      public void set(T obj, int newValue) {
49          unsafe.putIntVolatile(obj, offset, newValue);
50      }
51  
52      @Override
53      public void lazySet(T obj, int newValue) {
54          unsafe.putOrderedInt(obj, offset, newValue);
55      }
56  
57      @Override
58      public int get(T obj) {
59          return unsafe.getIntVolatile(obj, offset);
60      }
61  }