And the difference between the use of synchronized and lock

--- --- restore content begins

1. threads and processes

A program requires at least one thread, a process that requires at least one thread in -> Process -> Programs

A thread is the smallest unit of program execution flow, the process is an independent unit of system resource allocation and scheduling.

Several important method of 2.Thread

①start () method: Before you begin this thread

②stop () method: force the end of the thread

③join (): Wait for the end of the thread

④sleep () method: the thread into the wait

⑤run () method: direct execution run method of this thread (thread calls start () method will execute the run, the run method is distinguished by a thread scheduler to run the run method, a direct calling thread)

Note: wait () and notify () method is the object of, respectively, the thread suspend and resume a thread

Difference wait () and sleep () is: wait () releases the object lock, sleep () does not release the object lock

3. Thread State

There are five large state thread

Before the new thread object, start and did not call: ① new state

② ready state: After the start method is called to enter the ready state, other times thread recovery during sleep and suspend the state will enter the ready

③ running state: the thread is set to run the current thread begins execution method

④ blocked: the thread is suspended. For example, after calling sleep method

⑤ state of death: the end of the thread execution

4. lock type

① reentrant lock: In the execution object all synchronization methods do not get the lock again

② can break a lock: interruptible waiting to acquire the lock process

③ fair locks: the waiting time to obtain a lock carried by waiting threads acquisition, have the power to priority access to the lock wait a long time

④ read-write locks: read and write to resources when split into two parts processing, multi-threaded read when you can read together, the time to write must be written sync

 

java each object can be used as a lock, lock There are four levels, according to the order of lighter to heavier divided into: no lock, tend to lock, lock lightweight, heavyweight lock. Each object is a lock-free start, with the lock contention between threads, the more intense, the higher the level of the lock and the lock can only upgrade can not be downgraded.

A lock mechanism similar to java objects head closely, all the information lock are recorded in the object header of java, with 2 words (32 bits JVM 1 word = 32bit) memory object header, if array type is 3 words stored (also need to store the length of the array), the object header recorded in a hash value, pointer GC age, state of the lock, the thread owner, type of metadata


 

The difference between synchronized and lock

category synchronized lock
Level of existence Java keywords on jvm level It is a class
Lock release

1. to acquire the lock thread execution synchronization code, the lock is released

2. Thread execution exception occurs, jvm will thread releases the lock

Must release the lock finally in, or is likely to cause thread deadlock
Lock acquisition Suppose A thread gets the lock, B thread to wait, if A thread is blocked, B thread will wait Divide the case may be, Lock has a way of acquiring multiple locks, you can try to acquire the lock, the thread may not have to wait
Lock status Can not judge You can judge
Lock Type Reentrant, can not be interrupted, unfair Reentrant, it can be determined, be fair (both available)
performance A small amount of sync Large number of simultaneous

Lock interface methods

①lock (): to obtain a lock if the lock is then waits for temporary use

②unlock (): release the lock

③trylock (): return type is boolean, if acquiring the lock when the lock is occupied returns false, true otherwise

④tryLock (long time, TimeUnit unit): Compared to tryLock () is given a time limit to ensure that waiting time parameters

⑤lockInterruptibly (): a way to get the lock, if the thread enters the stage waiting to acquire a lock, you can interrupt this thread, to do something else

The underlying implementation of other kinds of locks

 

synchronized: View Source can know synchronized mapped into bytecode instructions is increased to pull instructions:. monitorenter and monitorexit When a thread encounters monitorenter execution of instructions, he will try to get a lock, then the lock is obtained if the lock count + 1, because it is a reentrant lock, it is necessary to use the lock count determination lock case, if a lock is not obtained, then blocked when it encounters monitorexit, the lock count of -1, when the counter is zero, it will release the lock.

Two synchronized lock release mechanism, the release of one is finished executing, another exception transmission is, the virtual machine is released, the second monitorexit FIG exception process is executed occurs, goto instruction in line 13, meaning that if normal operation will jump to the end of the 19-line execution

lock: synchronized is a pessimistic lock, shut himself up to work every time, for fear of being robbed and lock the bottom is the embodiment of CAS optimistic locking, the outside world does not matter if robbed, get re very optimistic, mainly on the ground floor volatile and CAS implementation

Note: as far as possible without going to use synchronized using lock

When jdk1.6 ~ jdk1.7, that is synchronized16,7年的时候 done a lot of optimization

6.synchronized role

synchronized method or block of code can be guaranteed at the same time run only one thread can enter the critical region, while ensuring the visibility of shared variables to other threads

Synchronized JDK1.6 before a heavyweight lock, is called a lock monitor (monitor) is achieved through an internal object, but the monitor is dependent on the nature of the underlying operating system Mutex Lock achieved, the operating system This realized switching between threads requires transition from user mode to kernel mode

optimization:

① threads spin and spin adaptability

java thread is actually mapped on top of the kernel, the thread suspend and resume will greatly affect the cost and jdk officials found that many threads while waiting for the lock, in a very short period of time to get a lock, so when they waiting threads, the thread does not need to be suspended, but let him aimless cycle, generally set 10 times, thus avoiding the overhead of thread switching, greatly improved performance. The adaptive spin, spin is given a learning ability, it is not fixed spin about 10 times. He can spin the thread of the case before it, to adjust it spin. Even without the spin hang directly

② locks elimination

Lock eliminate unnecessary synchronization is to be removed at compile time, eliminating the lock here does not necessarily mean you write the code lock eliminated.

For example stringBuffer is a safety class, it performs a simple method append string concatenation, append method will be synchronized, but the analysis can know that there is no thread-safety issues, then it will eliminate this synchronization lock

③ lock coarsening

When using synchronized, all pay attention to avoid large overhead, although synchronized block to be small, why it bold. Which stringBuffer concatenate strings, every time a append need to be synchronized, it can lock coarsening to the first and last append

④ lightweight lock

⑤ biased locking

 

--- end --- restore content

Guess you like

Origin www.cnblogs.com/xiaoyinger/p/11614587.html