Use AbstractQueuedSynchronizer to manage resource - Java Thread

Java examples for Thread:ConcurrentLinkedDeque

Description

Use AbstractQueuedSynchronizer to manage resource

Demo Code



import java.lang.reflect.Field;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

import sun.misc.Unsafe;

public class AbstractQueuedSynchronizerTest
{
    public static class StateTestParent
    {//from   w  w w.  ja  va2s.  c  om
        private static final Unsafe unsafe = getUnsafe();
        
        private static final long stateOffset;
        
        private int state;
        
        static
        {
            try
            {
                stateOffset = unsafe.objectFieldOffset(StateTestParent.class.getDeclaredField("state"));
            }
            catch (Exception e)
            {
                throw new Error(e);
            }
        }
        
        private static Unsafe getUnsafe()
        {
            try
            {
                
                Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
                singleoneInstanceField.setAccessible(true);
                return (Unsafe)singleoneInstanceField.get(null);
                
            }
            catch (IllegalArgumentException e)
            {
                throw e;
            }
            catch (SecurityException e)
            {
                throw e;
            }
            catch (NoSuchFieldException e)
            {
            }
            catch (IllegalAccessException e)
            {
            }
            return null;
        }
        
        public int getState()
        {
            return state;
        }
        
        protected final boolean compareAndSetState(int expect, int update)
        {
            return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
        }
    }
    
    public static class SelfStateTest extends StateTestParent
    {
        public void test()
        {
            int s = this.getState();
            this.compareAndSetState(s, 5);
            System.out.println(this.getState());
        }
    }
    
    public static class SelfAQS extends AbstractQueuedSynchronizer
    {
        private static final long serialVersionUID = -1732371754796453064L;

        public void test()
        {
            int s = this.getState();
            this.compareAndSetState(s, 5);
            System.out.println(this.getState());
        }
    }
    
    private void testUpdateAQSState()
    {
        SelfAQS selfAQS = new SelfAQS();
        selfAQS.test();
    }
    
    private void testUpdateSelfState()
    {
        SelfStateTest selfState = new SelfStateTest();
        selfState.test();
    }
    
    public static void main(String[] args)
    {
        AbstractQueuedSynchronizerTest test = new AbstractQueuedSynchronizerTest();
//        test.testUpdateAQSState();
        test.testUpdateSelfState();
    }
    
}

Related Tutorials