Reflection-introspection-proxy mode-reentrant lock under concurrent library in java

thread safety
 ---------------
    1. Synchronization
        Synchronized code block
        Synchronized method
    2、synchorize
        Any object in java can be used as a lock flag.
        A waiting queue is maintained inside the object.
        Multi-threaded programming involves the production and consumption relationship, which can be done with the help of queues.
        lock.wait()
        lock.wait(int n) ;
        lock.notify()

    
    3. The difference between sleep and wait
        sleep loses the cpu preemption right, and has nothing to do with locking.
        wait() loses the cpu preemption right and loses the lock.

Disadvantages of sync synchronization
----------------
    higher cost,
    Reente
    100 tickets 2 individual conductors
    ------------------    
    sync        18,826,327ns
    lock        18,506,514ns    


ReentrantLock under concurrent library
------------------------
    1.ReentrantLock
        System resource consumption is less.
        ReentrantLock lock = new ReentrantLock() ;
        //上锁
        lock.lock();

        // Unlock 
        lock.unlock();

    2.ReentrantReadWriteLock
        Reentrant read-write locks with finer granularity.
        Equivalent to optimistic locking, it supports a certain degree of concurrency.
        Read locks are also called shared read locks (shared).
        A write lock is also an exclusive write lock (exclusive).
        
        Thread 1 Thread 2. Read lock     |     Thread 2. Write lock
         ------------------------------------- ------------ 
        readLock()     | ok |     not ok
         ------------------------------ ------------------- 
        writeLock()     | not ok |     not ok


ReentrantLock.lock()
------------------------
    1. Explanation
        If the lock is not held by another thread, the counter is set to 1 when the lock is requested.
        If the lock is currently held, the counter increases by 1 and returns immediately.
        If the lock is held by another, the current thread is unavailable and sleeps until the lock is acquired.
        and reset the counter to 1.

ReentrantLock.tryLock()
------------------------
    1. Explanation
        Try to lock, if other threads are not locked, return immediately after locking, the counter returns to 1,
        Returns false immediately if the thread is locked.

FairSync and NonfairSync
------------------------
    Fair synchronization and unfair synchronization mechanisms.
    The fair synchronization is the queuing mechanism, and the unfair mechanism is the random mechanism.
    The default is the unfair mechanism, which is similar to the mechanism of the notify() method.
    Reentrant locks are implemented internally through synchronization objects, and synchronization objects are divided into fair and unfair.


Unsafe objects use the CAS mechanism to achieve atomicity
-----------------------
    1. Introduction
        compareAndSwap(), compare and swap.

        i ++
        i=1
        long i = 1 ;//32

volatile
----------------------
    1. Introduction
        Volatile, unstable, and visible in real time.
        After the member variable modified with this keyword is modified by a thread, it will be seen by other threads immediately.
        On the contrary, other threads may still read the value before the modification.

Operations on AtomicInteger Atomic Integers
--------------------------
    1. Introduction
        This class encapsulates an integer inside, and the operation of the integer is implemented through the underlying unsafe class to meet the atomicity requirements.
        A number of corresponding methods are provided:
        getAndIncrement()         // int y = i ++ , add and subtract 
        incrementAndGet()         // int y = ++ i , 

        getAndAdd( int x)         // int y = i ++ x

Concurrency library and sun underlying library
-------------------------
    ReentrantLock
    ReentrantReadWriteLock
    AtomicInteger
    sun.misc.Unsafe


reflection
--------------------------
    1、Class
        Class class is the descriptor of the class, which describes the properties of the java class.

    2. Method
         class .declaredMethods()         // Declared methods. 
        class .methods()                 // All visible methods.

    3、Field
        fields, member variables.
        Field f = class.getDeclaredFiild("name") ;

    4、Constructor
        Constructor, constructor, constructor.
        // Class descriptor 
        Class clazz1 = Cat.class ;
        Constructor ctor1 = clazz1.getDeclaredConstructor(String.class) ;
        //
        ctor1.setAccessible(true);
        Object obj = ctor1.newInstance("tom");
        System.out.println(obj);

    5. Deserialize objects without construction.
        Deep copying is achieved through java serialization technology.
        The java class needs to implement the java.io.Serializable interface. There is no method to change the interface. It is an identifying interface.
        Give the jvm a tag. Member variables modified with transient do not participate in the serialization process and remain null.
        Transient can reduce memory consumption, avoid the construction of unwanted objects, and save memory.
        serialVersionUID The serial ID is mainly used in the anti-serial process to complete the version comparison of the class.
        Cat  cat = new Cat();
        cat.setName("tom");
        cat.setAge(12);

        FileOutputStream fos = new FileOutputStream("d:/cat.dat") ;
        ObjectOutputStream oos = new ObjectOutputStream(fos) ;
        oos.writeObject(cat);
        oos.close();
        fos.close();

    6. Whether the deserialization goes through the constructor
        The constructor is not passed through when deserializing. Because it is not necessary, the serialized object is the state (member variable),
        After serialization, the state is fixed, and it only needs to be restored to the corresponding state when deserializing, and the constructor is
        In the process of creating an object, the ultimate purpose is to set values ​​on member variables.

    7. Attribute copy /** through reflection
        
         * Test property copy
         */
        @Test
        public void testPropertiesCopy() throws Exception {
            Cat a = new Cat() ;
            a.setName("tom");
            a.setAge(12);
            a.color = "red" ;

            Cat b = new Cat();
            copyProperties(a , b);
            System.out.println();
        }

        private static void copyProperties(Object a , Object b){
            try {
                Class aClazz = a.getClass();
                Class bClazz = b.getClass();

                // Get all fields of a object 
                Field[] fs = aClazz.getDeclaredFields();

                for(Field f : fs){
                    f.setAccessible(true);
                    Class ftype = f.getType();             // Field type 
                    String fname = f.getName() ;         // Field name 
                    Object value = f.get(a) ;             // Field value

                    try {
                         // Get the corresponding field in class b 
                        Field bf = bClazz.getDeclaredField(fname);
                        bf.setAccessible(true);
                        bf.set(b , value);
                    } catch (Exception e) {
                        continue;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
        

introspection
-------------------
    1. Introduction
        A tool class dedicated to manipulating javabeans, mainly accessed through methods.
        [Attributes]
            The name part corresponding to the getter / setter.
            getName()
        [field]
            Member variables


    2. Realize attribute replication
        @Test
        public void test1() throws Exception {
            Cat a = new Cat();
            a.setName("tom");
            a.setAge(12);
            a.setCategory("c1");
            Cat b = new Cat() ;

            copyProperties(a, b);
            System.out.println();
        }

        /**
         * Through introspection, manipulate javabeans, and realize the property replication of two objects.
         */ 
        public   static  void copyProperties(Object a , Object b) throws Exception {
             // Get the javabean information of the class 
            BeanInfo abi = Introspector.getBeanInfo(a.getClass()) ;
             // Get all property descriptors 
            PropertyDescriptor[] apds = abi .getPropertyDescriptors();

            // Get the javabean information of the class 
            BeanInfo bbi = Introspector.getBeanInfo(b.getClass());
             // Get all property descriptors 
            PropertyDescriptor[] bpds = abi.getPropertyDescriptors();

            // Iterate 
            for (PropertyDescriptor pd : apds){
                 // Get the property name 
                String name = pd.getName() ;
                Class apclazz=pd.getPropertyType() ;
                //getter
                Method getter = pd.getReadMethod();

                if(getter != null){
                    getter.setAccessible(true);
                    for(PropertyDescriptor pd0 : bpds){
                        String bpname = pd0.getName();
                        Class bpclazz = pd0.getPropertyType();
                        Method bpsetter = pd0.getWriteMethod() ;
                         // both ab objects have the same property name and type 
                        if (name.equals(bpname) && apclazz.equals(bpclazz) && bpsetter != null ){
                            bpsetter.setAccessible(true);
                            Object value = getter.invoke(a) ;
                            bpsetter.invoke(b , value) ;
                        }
                    }
                }
            }
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324903315&siteId=291194637