BAT American drops Java interview outline (with answer version) Four: multi-threaded lock

Source: Internet
Author: User
Tags cas static class

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code

This is the second chapter of multithreading.

Multithreading is like Kong Cong to the star-sucking Dafa, understanding the use of good can be attained to the immortal, overlooking the mortal beings, and abuse will be bite.

The second "robbery" to be crossed in multithreaded programming is lock. In many cases, including interviews, including actual project applications, we will compare them with synchronized.

We know that the core idea of multithreading is to increase the number of threads to run concurrently, to improve efficiency, that is, the number-winning theory, rather than the quality of the win (improve the processing capacity of each thread). One of the biggest challenges in multithreaded programming is how to solve variable value uncertainties caused by multiple threads modifying a common variable at the same time. Along this line of thought analysis, the common method, is nothing more than, either to the variable hands, when a thread modification, the value of the variable is locked. Either the modified operation is done, and when the code executes, it is locked and other threads cannot enter the code execution at the same time.

Like synchronized, Lock is the latter approach. Only, the implementation way, different.

Lock

  1. Q: Do you usually involve many multithreaded programming? Talk about your understanding of lock lock.
  2. Analysis: Better to compare with synchronized
  3. Answer:
    1.   In multithreaded programming, in order to achieve the purpose of thread safety, we tend to lock the way to achieve. Lock Lock is the Java code level to achieve, relative to synchronizedd in the functional, has been strengthened, mainly, fair lock, polling lock, timing lock, interruptible lock, etc., but also added a multi-channel notification mechanism (Condition), you can use a lock to manage multiple synchronization blocks. In addition, the lock must be released manually when used.
    2. Detailed analysis:
      1. The implementation of lock locks is achieved mainly through the use of queue Synchronizer (AQS, which we often see). It includes an int variable to represent the State, and a FIFO queue to store the queued thread that gets the resource.
      2. When a thread requests a resource, it is to get the current synchronization state and determine if it can be expected, or, if so, to modify the synchronization state of the int variable identity above, through the CAS operation. If no, the thread enters the queue (this is the general case, when using Tyrlock, it is directly returned to acquire the lock failure).
          1. Locks have exclusive and shared locks. The exclusive lock is the same time, only allow the same thread to hold the lock, the shared lock implementation of the time and the exclusive lock slightly different, not simply modify the synchronization state (such as 1 and 0), but rather to obtain this value, the values are greater than 0 o'clock, that is, the identity to obtain a shared lock success (implied that after each thread acquires a lock Attached to the implementation of the exclusive lock source code (source fragments from the "Java Concurrent programming Art", and add their own comments):
            public class Mutex implements Lock {//static inner class, custom Synchronizer private static class Sync extends Abstractqueuedsynchroni  zer{//This method is used to determine whether the current lock is occupied in exclusive mode protected Boolean isheldexclusively () {return getState () = =          1;         }//Get LOCK!!! public boolean tryacquire (int acquires) {
            A typical CAs atomic operation, if the initial state is 0, can obtain the lock if (compareandsetstate (0, 1)) {Setexclusiveownerthread (Thread.curr Entthread ()); return true; } return false; }//Release lock, set the current state to 0 protected boolean tryrelease (int releases) {if (getState () = = 0) { throw new Illegalmonitorstateexception (); } setexclusiveownerthread (NULL); SetState (0); return true; }//Returns a Condition, each Condition contains a Condition queue, which is followed by Condition Newcondition () {return n EW Conditionobject (); } }

      3. Lock lock, which supports interruptible locks, the principle is that waiting threads in the queue can respond to interrupt signals initiated by other threads and throw interruptdexception exceptions.
      4. With regard to the synchronization queue, it is necessary to understand that the thread that gets the synchronization state failed, is wrapped as node, joins the tail of the queue, this operation is a CAS operation to ensure thread safety, failure is a dead loop retry, and the first node of the queue is the thread that currently holds the lock. Once the node releases the lock, the successor node is awakened.
      5. With regard to wake, this is the case that each blocking thread in the synchronization queue is in a spin state and is constantly trying to acquire a lock. In this way, when the first node releases the wake-up thread after the lock wakes up, it also needs to determine if the former thread is the first thread, and then the synchronization state (lock) succeeds.

4. Extension: Condition, multi-channel notification mechanism

  

    1. In the synchronized lock, wait, notify, Notifyall and so on are provided, and the waiting/notification mode is implemented. Then in lock, a similar pattern is implemented by condition mates.
    2. The essence of the implementation is that a condition contains a wait queue, defining multiple condition, and then there are multiple wait queues, which are used in conjunction with the synchronization queues mentioned above. Synchronization queue-Wait queue model refer to:
    3. In the above model, calling the await method is equivalent to moving the first node of the synchronization queue (the thread holding the lock) to the waiting queue. Calling the signal method to wake up a blocked thread is to move the first node in the corresponding condition wait queue (the longest waiting time) into the synchronization queue.
    4. There is also a need to add, that is, the wake of the thread, call signal can wake up normally, terminate the thread in other threads, also wake up, just wake up, only throw interruptexception exception.

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code

BAT American drops Java interview outline (with answer version) Four: multi-threaded lock

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.