After three face

Spring said about the loading process in the bean, BeanFactory and FactoryBean What is the difference

Outline

Spring as Ioc framework to achieve dependency injection, consists of a centralized plant Bean responsible for instantiating each dependency management and the Bean. Bean can each do not care about their complicated creation process to achieve good decoupling effect.

We conducted a cursory summary of the workflow Spring, mainly into two areas:

  • Parse , read xml configuration, scanning the class file, obtain Bean definition information from the configuration or annotation, the registered number of extensions.
  • Load , get information analysis Bean instance by defining finished. We assume that all configuration and extension classes have been loaded into the ApplicationContext, and then analyze the specific loading process of Bean.
  • Scope . Scope singleton or prototype scope, singleton, then need a global instantiated once, each time you create a prototype needs to be re-instantiated.
  • Dependencies . Bean If there is a dependency, we need to initialize dependency, and then associate. If there is a circular dependency, A dependent B, B-dependent C, C are also dependent A, this solution requires a plurality of circular dependencies among Bean.

2. Overall Process

  • Get beanName , incoming name is parsed into can be obtained from the Map to BeanDefinition the bean name.
  • The combined Bean definitions , the definition of the parent class of the merger and coverage, as well as the parent if the parent class will recursively combined to get the full Bean definition information.
  • Instantiation , Bean instance is created using the constructor or factory method.
  • Filling properties , and look for injecting dependencies, Bean will depend on the recursive call getBeanmethod to get.
  • Initialization , initialization method is called custom.
  • Obtaining final Bean , if it is FactoryBean need to call getObject method, if you need to call TypeConverter type conversion transformation.

BeanFactory and the difference FactoryBean

BeanFactory ending Factory's, indicating that it is a factory class for managing a factory Bean

             In Spring, Bean are all to be managed by the BeanFactory (ie IOC container).

     But FactoryBean is concerned, this is not a simple Bean Bean, but a capable of producing or modifying objects generated by factories Bean,

             Its implementation is similar to the design model of the factory model and modified mode.

 

 

How Synchronized underlying principle bytecode level to achieve lock

Application way

synchronized is a way to solve the most common Java concurrency, easiest method. Keywords can be synchronized to ensure at the same time, only one thread can access a method or a block of code. At the same time can also be synchronized to ensure that changes in a thread by another thread sees (to ensure the visibility)
to note here: synchronized heavyweight lock a mutex (details follow-speak)

The main role of synchronized three:

  1. Make sure that the thread mutually exclusive access code
  2. Ensure timely modify the shared variable visibility (visibility)
  3. You can prevent the JVM instruction reordering

All objects can be used as a lock in Java, which is synchronized to achieve basic synchronization.
synchronized There are three main applications:

  1. Common synchronization method, the lock of the object is the current instance
  2. Static synchronized method, the object lock is a class where the static methods
  3. Sync block, lock the brackets object. (May be instances where an object, the object may be a class type.)

Principle Summary

Java virtual machine synchronization (Synchronization) are based on entry and exit Monitor object implementation, (synchronous code block) or implicit synchronization (sync method) both display synchronization true.

  • Block synchronization code
    monitorenter instructions into the start position of the synchronization code block. monitorexitInstructions into synchronized block end position. JVM need to ensure that each monitorenterhas a monitorexitcorresponding.
    Any object has associated with it a monitor, when the monitor after being held, it is locked. When the thread execution to monitorenter instruction, will try to obtain monitor ownership of the object, that is trying to acquire the lock.

Virtual Machine specification of the behavior described monitorenter and monitorexit, there are two things to note. First synchronized with a thread for fast synchronization is reentrant, that is to say, without problems of their own lock. Secondly, synchronization has entered the fast before executing the thread can block back into the other threads. (Excerpt from "in-depth understanding of JAVA virtual machine")

  • Synchronization method
    synchronized method will be translated into ordinary method call and return instructions such as: invokevirtual, areturn instruction in the VM bytecode level and do not have any special instructions to implement the synchronized modified method, but the method Class files the table synchronized flag access_flags field method in position 1, which is represented using the synchronization method and the method is called Class object or an object which belongs to the internal representation of the JVM Klass as the lock object.

Detailed principles

To understand the low-level implementation, we need to understand two important concepts Monitor and Mark Word

  • Java object header

synchronized lock used, is stored in the object header. (This is also the root cause of all Java objects can be locked)
HotSpot virtual machine, the object head includes two pieces of information:
Mark Word (object header) and Klass Pointer (pointer type)

  • Wherein the type of pointer, the object is a pointer to its class element, the virtual machine is determined by the pointer which is an instance of the object class.
  • Object header is divided into two parts: The first part of the run-time data storage object itself, such as hash code, GC generational age, thread holds the lock, bias timestamp. The length of this part is not fixed. The second part is the end of the two storage lock flag indicates the current lock level.

Object header length typically occupy two machine code (32-bit JVM, a machine code equal to 4 bytes, i.e. 32bit), but if the object is an array type, the machine code requires three (a plurality of recording an array length).

FIG changes the state of the object when the first operation :
the lock flag and whether or not biased locking determine only the locked state
wherein the light quantity after the lock and biased locking JDK1.6 newly added, synchronized for optimization. Mentioned later

java object head
  • Monitor

Monitor is synchronized heavyweight achieve key lock. Lock flag is 10 . Of course, synchronized as a weight lock is very performance consuming, so after JDK1.6 made some optimization, the next part is about as achieve weight lock.

Monitor is thread-private data structure, each object has a monitor associated with it. Each thread has a list of available monitor record (monitor all the objects in the current thread), along with a list of available global (global object monitor). Each locked object, and will be associated with a monitor.

When a monitor is held by a thread, it will be locked. In this case, the target head MarkWord directed mutex pointer is pointing to the starting address of the monitor lock object .
ObjectMonitor monitor is implemented, the main data structure is as follows :( located HotSpot VM ObjectMonitor.hpp source files, C ++ implementation)

ObjectMonitor() {
    _header       = NULL; _count = 0; //记录个数 _waiters = 0, _recursions = 0; _object = NULL; _owner = NULL; _WaitSet = NULL; //处于wait状态的线程,会被加入到_WaitSet _WaitSetLock = 0 ; _Responsible = NULL ; _succ = NULL ; _cxq = NULL ; FreeNext = NULL ; _EntryList = NULL ; //处于等待锁block状态的线程,会被加入到该列表 _SpinFreq = 0 ; _SpinClock = 0 ; OwnerIsThread = 0 ; } 

There are two queues object monitor _EntryListand _WaitSetis used to save ObjectWaiter object list (each thread will wait for the lock to be packaged ObjectWaiter Object) _ownerthread held objectMonitor of points.

When multiple threads access a synchronization code, will enter the first _EntryListset, when the monitor thread to obtain the object, will enter _owner region, then the monitor is _ownervariable as the current thread, and monitor the counter _countwill add 1 .

According to the requirements specification of the virtual machine, in the implementation of monitorenter instruction, it will try to lock acquisition targets. If the object is not locked (to obtain a lock), get the object that thread has been locked (locked reentrant). Put the counter is incremented by 1 ( _countplus 1). Accordingly, when executing instructions monitorexit, speaks counter is decremented. When the counter is 0, _owner point Null, the lock is released. (Excerpt from "in-depth understanding of JAVA virtual machine")

If a thread calls wait()the method, will release the monitor currently held, _ownervariable recovery is null, _countvariable minus 1, while the thread enters _WaitSetwaiting to be awakened.


The underlying implementation

  • Lower principle synchronized code block

The compiled bytecode can be seen from Javac (specifically see reference links the compiled file), the synchronized block monitorenterand monitorexitinstructions, which monitorenterpoints to the start position of the synchronization code block monitorexitto the end-position of the synchronization code block.

Thread execution to the monitorenterinstruction, the current thread attempts to acquire a lock, that is trying to acquire the right to hold the lock object corresponding to the monitor. When the monitor's count counter is zero, or monitor the owner is already a thread, you get a lock, count + 1 counter.
If another thread already holds the lock of the object, the thread is blocked until the other thread releases the lock is finished.

When the thread is finished, count zero, owner point to Null, the lock is released.

It is noteworthy that the compiler will ensure that, no matter what method is accomplished by the method of each monitorentercommand, eventually there will be monitorexitcorresponding to the command, regardless of the method of normal or abnormal end, eventually pairing execution.
The compiler automatically generates an exception handler, the processor can handle all exceptions statement, its purpose is to ensure that the monitorexitinstruction final execution.

 

  • synchronized low-level method principle

The method of implicit synchronization stage, i.e. without the need to control the byte code, which implements the call and return operations in the process.
Class file table structure in the process of the method in the constant pool (method_info Structure) In, ACC_SYNCHRONIZED access flag as a synchronization method of distinguishing method. When the method is called, ACC_SYNCHRONIZED inspection methods would flag is set. If set, it will hold the thread monitor (instance object class object method call or static method) which corresponds to the object, and then perform the method.
Finally, when the method execution is completed, the release monitor.
During method execution, execution thread holds the monitor, no other thread can no longer obtain the same monitor.
The following is a bytecode:

public class SyncMethod {

   public int i; public synchronized void syncTask(){ i++; } } 

Use javap decompile the byte code as follows:

Classfile /Users/zejian/Downloads/Java8_Action/src/main/java/com/zejian/concurrencys/SyncMethod.class
  Last modified 2017-6-2; size 308 bytes
  MD5 checksum f34075a8c059ea65e4cc2fa610e0cd94
  Compiled from "SyncMethod.java"
public class com.zejian.concurrencys.SyncMethod
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool;

   //省略没必要的字节码
  //==================syncTask方法======================
  public synchronized void syncTask();
    descriptor: ()V
    //方法标识ACC_PUBLIC代表public修饰,ACC_SYNCHRONIZED指明该方法为同步方法
    flags: ACC_PUBLIC, ACC_SYNCHRONIZED
    Code:
      stack=3, locals=1, args_size=1
         0: aload_0
         1: dup
         2: getfield      #2                  // Field i:I
         5: iconst_1
         6: iadd
         7: putfield      #2                  // Field i:I
        10: return
      LineNumberTable:
        line 12: 0
        line 13: 10
}
SourceFile: "SyncMethod.java"

As can be seen from the bytecode, synchronized method is not modified monitorenterand monitorexitinstructions. But with ACC_SYNCHRONIZEDa flag to indicate if synchronization method is a method to perform a corresponding synchronous call.

 

"Unfair lock" and "fair lock" the difference between how unfair ReentrantLock achieve lock

1 ReentrantLock and synchronized difference

  (1) synchronized Java is a built-in keywords, and ReentrantLock is a Java class.
  (2) synchronized only non-fair locks. The ReentrantLock can achieve fair and unfair lock other kinds of locks.
  (3) synchronized can not interrupt a thread waiting for the lock, and Lock can interrupt a thread attempts to acquire a lock.
  (4) synchronized time-out can not be set, and Lock timeout can be set.
  (5) synchronized automatically release the lock, and ReentrantLock not automatically release the lock must be manually released, as this may lead to deadlock.

Lock the difference between fair and unfair 2 locks

(1) thread calling lock lock in access (), unfair lock will first conduct a CAS try to grab a lock, if at this time there is no thread holds the lock, or just at the moment there is a thread executing the release lock (state == 0), so if CAS is successful direct holding the lock to return.
(2) If a non-equity locked up in the previous step to acquire the lock fails, it will enter nonfairTryAcquire (int acquires), in which, if the state value of 0 indicates that no thread holding the lock, or just have a thread releases the lock , it will lock CAS grab, grab, if successful, will return directly, whether or not there are other threads waiting to lock in long queues in the blockage. And fair locked in here to grab a lock, will judge blocked the queue is not empty, after all, to be fair we should say first come first served, if you find blocking queue is not empty, represent a queue already waiting for the other thread, so fair lock case thread will obediently discharged at the end of blocking queue.
  If the non-fair locks (1) (2) fail, then the rest of the process is unfair and lock the same.
(3) (2) it can be seen from (1), may lead to unfair lock thread starvation, but unfair lock higher efficiency.

 

 

concurrentHashmap it is safe, concurrentHashmap how the size requirements

Under concurrency scenarios, you need to how to set the lock

What use mysql index

Mysql present, there are several index types: FULLTEXT, HASH, BTREE, RTREE .
1. FULLTEXT

is the full-text index, only MyISAM engine support. It can be CREATE TABLE, ALTER TABLE, CREATE INDEX use, but can now create full-text index is only CHAR, VARCHAR, TEXT columns.

MyISAM and full-text indexing is not born together, it appears to solve the "% word%" low efficiency of this type of fuzzy search for the text of the problem WHERE name LIKE.
HASH 2.

As the sole (the sole of almost 100%) and the like HASH key-value pairs, it is suitable as an index.

HASH index can locate one, do not need to look like a tree indexes as layer by layer, and therefore has a very high efficiency. However, this efficiency is conditional, that is, only the "=" and "in" under conditions effective for the scope of inquiry, ordering and combination index is still inefficient.
BTREE 3.

BTREE index is a kind of index value by a certain algorithm, into a tree data structure (binary tree), each query begins at the entrance root of the tree, in order to traverse node, obtain leaf. This is the default in MySQL and the most common type of index.
RTREE 4.

RTREE rarely used in MySQL, supports only geometry data type, the type of storage engine supports only MyISAM, BDb, InnoDb, NDb, Archive few.

Relative to BTREE, RTREE strength lies in the range of search.

 

 

B + tree index how fast (B + tree advantages)

  1. B + tree height is generally 2-4 layers, so that a maximum of only 2-4 times IO find records, relatively balanced binary tree has been greatly reduced.
  2. The range of search, by acquiring the data pointer to leaf nodes. Equal to the data such as finding 3, as found in the 3 leaf nodes, all of the data acquired by the tail pointer 3 will be able, without the need to re-acquired as a binary tree as the parent node 3.

 

 

What phantom read, how to avoid phantom read Innodb

Magic Reading under MVCC innodb by GAP or lock or next-key lock solution of

Lock lock range of the gap is much

JVM memory model

Gc difference between the types mingc and fullgc what happened when gc

     New Generation GC (Minor GC): refers to the place in the new generation garbage collection action, because most of Java objects with
    equipment characteristics Chaosheng evening off, so Minor GC very frequently, usually recover relatively fast speed.

     Old's GC (Major GC / Full GC) : GC refers to occur in old age, there was Major GC, often
    accompanied by at least one of the Minor GC (but not absolute, in the collection strategy ParallelScavenge Collector's
    there directly Major GC strategy selection process). MajorGC generally slower than the speed of Minor GC 10
    or more times.

Minor GC trigger mechanism:
when the young generation is full it will trigger Minor GC, where the young generation full refers to the generation of full Eden, Survivor will not lead to full GC.
Full GC trigger mechanisms:
(1) When you call System.gc, the system proposes the implementation of Full GC, but not necessarily execution
(2) years old and insufficient space
(3) the method area is insufficient space
(4) years old on average enter through the Minor GC old age is greater than the size of the available memory
(5) by the Eden region, survivor space1 (From Space) region survivor space2 (to Space) time zone replication, the object size is larger than the available memory to Space, put the subject's old dump, years old and the available memory is less than the size of the object

When the permanent generation of full will lead to Full GC, it will lead to uninstall Class, Method meta-information.

 

 

 

volatile underlying implementation

Multi-core cpu cpu how to achieve the level of visibility in

Difference and implementation of hashmap and concurrenthashmap

Hashmap is essentially an array plus a linked list. The key to obtain the hash value, then the calculated array index, if the key corresponds to a plurality of the same index, to use the list to string together, in front of the newly inserted.

  ConcurrentHashMap: hashMap on the basis, of ConcurrentHashMap data into a plurality of segment (segments), default 16 (concurrency level), and each operation on a segment (segment) lock, to avoid the chance of lock multithreading, increasing concurrency effectiveness.

HashMap is not thread-safe, and is thread safe ConcurrentHashMap

 

string stringbuffer stringbuilder differences and achieve

Guess you like

Origin www.cnblogs.com/ashin1997/p/11602979.html