[Java reviewing 05] concurrent multi-threaded & knowledge supplement

0. wait / notify / notifyAll understanding?

  wait: let the thread holds the object lock wait;

  notify: wake up any thread holds the object lock;

  notifyAll: wake up all the threads holding the object lock;

  Their relationship is three, call the object's method to make a thread wait pause run by notify / notifyAll method of temporarily wait thread wakes up call.

  They are not in the method of the Thread class, but the Object class, and why?

  Because each object has a lock monitor thread to operate an object of course is to get a lock of an object, rather than a thread lock.

  important point:

  1, the call object wait, notify, notifyAll methods need a monitor lock object, i.e. they can only be used in the synchronization method (block);

  2, call the wait method uses thread pause and let the CPU resources, while releasing the lock held by the object;

  3, the use of multi-threading notify prone to deadlocks generally used notifyAll;

 

Difference 1. sleep () and wait () is?

  1.1 LIMITATIONS (exception trap)

  sleep () thread to sleep, time to proceed, we need to capture InterruptedException.

  wait () must be synchronized into a synchronization code blocks, the same need to capture InterruptedException exception and needs to acquire the lock object.

  The method also requires additional wait notify / notifyAll wakes up, they also need to be placed inside the synchronized block, and acquiring the lock object.

  notify / notifyAll do not need to catch the exception, but the wait still need to capture InterruptedException.

   1.2 usage scenarios

  typically sleep for the current thread to sleep or suspend polling operation, wait is used for communication between multiple threads.

  1.3 belongs to class

  Thread class is a static sleep native method, wait native method is the Object class.

  Why this design?

   Because sleep is for the current thread to sleep, not related to the object class, the object does not need to acquire a lock, so is the method of the Thread class.

   wait is to get the thread to achieve the object lock wait, the premise is to get the object's lock Chu, so is the method of the class.

  1.4 release lock ( the wait will release the lock, notify just notice, does not release the lock )

  wait can release the current thread holds the object lock to lock, but sleep does not.

  wait (), notify () and notifyAll () method is a local method, and a method for the final and can not be rewritten.

  The current thread must own this object's monitor (ie lock) to call an object's wait () method allows the current thread blocked.

  This blockage is synchronized by early release lock, blocking lock request to re-caused, such a request must be re-awakened by other threads compete for locks notify () or notifyAll ().

  Call an object notify () / notifyAll () method can wake up more than a / are waiting for the object monitor thread.

  notify () or notifyAll () method is not really release the lock, you must wait until the synchronized method or block executing the grammar really release the lock.

 

2. Join the use and principles?

  join () method of the Thread class Thread, definition refers to the current thread to wait after the end of the thread to continue .

  The main thread calls t.join () will block the main thread, the thread is finished until t.

  Principle: be implemented using the wait method. When the main thread calls method main thread t, the main method to get to the object lock t's,

             The t wait method calls itself by blocking whenever t the end of the time before or after exit, then wake up the main thread to continue.

 

3. Thread sleep, half-way calling thread.interrupt () What happens?

  Interrupt can interrupt sleep the current thread, and throw InterruptedException.

 

4. synchronized There are several uses?

  1. The common method of synchronization

     The same instance only one thread can acquire the lock to enter this method.

     Acts on only a single instance, multiple instances, failure of the synchronization method.

  2. Synchronize static method

     No matter how many instances of the class, only one thread can acquire the lock to enter this method.

  3. synchronization classes

    Pinning effect and synchronous static methods, are class-level locks, only one thread can access method with synchronous class lock.

  4. Examples of this synchronization

      This usage is synchronized block, lock the entire current object instance represents only get to this instance of the lock to enter this method.

     Common usage and synchronization methods lock, are locked throughout the current instance.

  The synchronization object instance XXX

  This is also the usage of sync blocks, and lock the current instance of the above, as shown here lock the entire object instance XXX, XXX only get to this instance lock to enter this method.

  important point:

  Example lock Locks are not mutually obstructive, but the same type locks, the lock current instance of the same, the same object will block lock each other.

 

The realization principle of the method of code synchronization and block synchronization?

  JVM sync block synchronization and code-based objects to enter and exit Monitor implemented method may be used monitorenter and monitorexit instructions.

  monitorenter instruction is compiled at the start position of the synchronization code is inserted into the block and is inserted into the monitorexit instruction anomaly and the method ends,

  JVM monitorenter ensure that each has a threshold value corresponding to monitorexit. Thread execution to monitorenter time, will try to get the monitor lock object corresponds,

  Before you can get access to the lock synchronize the use of Java objects stored in the header.

 

6. synchronized implementation principle?

  synchronized based Monitor (object monitors) to achieve synchronization.

  Monitor two ways to support the synchronization between threads: exclusive execution, collaboration

  1. Java using the object lock (obtained using synchronized object lock) ensure worker threads on a shared data set mutually exclusive execution.

  2. wait / notify / notifyAll method to work between the different threads.

  3. Class and Object is associated with a Monitor.

  Monitor working mechanism:

  After entering the thread synchronization method,

  In order to continue to perform critical section, a thread must acquire the lock Monitor. If you acquire a lock is successful, it will become the owner of the watcher object.

  Within any one time, the supervisor objects belong to only one active thread (The Owner).

  Who has monitored object thread can call wait () wait to enter the set (Wait Set), while monitoring the release of the lock, enter the wait state.

  After the code can execute wait after another thread calls notify () / notifyAll () interface to set the wake-up waiting threads, these threads need to wait for the monitor to reacquire lock ().

  Synchronization method is finished, the thread exits the critical region, and release the monitor lock.

 

7. The concrete realization of synchronized?

  1, the synchronization code blocks using monitorenter, monitorexit instruction explicitly implemented.

  2, the implicit synchronization method implemented ACC_SYNCHRONIZED marker used.

  monitorenter:

  Each object has a monitor, a monitor can only be a thread owns.

  When a thread attempts to execute the monitorenter instruction obtain the corresponding object monitor, access rules are as follows:

    If the number entering the monitor is 0, then the thread can enter the monitor, and the monitor is set to enter the number 1, shall monitor the thread owner.

    If the current thread already owns the monitor, only to re-enter, then enter the number into the monitor plus 1, so to achieve the synchronized keyword lock is reentrant lock.

    If the monitor has been owned by other threads, the current thread into the blocked state, until the number into the monitor to 0, and then again try to obtain monitor.

  monitorexit :

    Only those with the appropriate object monitor thread can execute monitorexit instruction.

    Each time the instruction enters monitor minus one, when released into the number of the current monitor thread is 0:00, then the blocked thread will attempt to acquire the monitor.

  Lock storage location:

  Lock mark in the Mark Word Java objects stored in the head.

  synchronized lock optimization:

  JDK1.6 introduced "biased locking" and "lightweight lock." 4 lock status: No Lock -> biased locking -> Lightweight locks -> Lock heavyweight

 

8. JMM principle of shared variables to read and write?

  Each thread has its own working memory, each thread must first share when the need for shared variables manipulated variable from main memory to load their working memory, such as when the operation is completed and then save the shared variable to main memory.

 

9. Memory invisible problem?

    If a thread is not finished brush operation to main memory, then the value of the shared variable by another thread to read from the main memory,

    This time read data is dirty data, and it overrides the other end of the calculation of the value of the thread.

 

10. volatile realization of the principle of?

  Lock prefix 1. JVM command will cause the CPU cache is written back to system memory.

  2. In order to ensure cache consistency principle, in a multi-CPU scenarios, a CPU cache write-back cache memory causes the other CPU fail, will visit again to reload a new cache content from the system memory.

 

11. HashMap is not thread safe?

    Scene 1: HashMap as local variables within the method, thread-safe!

    When local variables inside methods, local variables belonging to the current thread-level variables, other threads can not access, so security.

    Scene 2: The object member variable, unsafe!

    What are the thread-safe Map?  

    1. HashTable

        get / put methods are modified synchronized keyword, but the same thread can only get or put, low efficiency.

    2. SynchronizedMap

private Map<String, Object> map = Collections.synchronizedMap(new HashMap<String, Object>());

     The incoming synchronized HashMap packaging, implementation is to add mutex object lock, the performance is not good.

    3. ConcurrentHashMap - Recommended

       Before the lock segment JDK1.8, the tub 16 minutes, each time adding only a lock barrel.

       JDK1.8 joined CAS red-black tree algorithm and improve efficiency.

12. JDK1.7 and JDK1.8 realization of the principle of ConcurrentHashMap about?

    In java 7, the realization is achieved ConcurrentHashMap segment lock protocol based, in essence, is the use of locks.

    Just based on one consideration is that multiple threads access a hash bucket random, based on such considerations will be different hash section above, and then each segment with a lock data storage,

    The need to write a segment of the lock when needed, but at this time, other threads to access other sections of blocking is not required,

    But for this segment of threads access will have to wait until the thread releases the lock of the lock, other threads can access it. 

    In java 8 in, ConcurrentHashMap abandoned the realization of this complex architecture, but inherited the idea of ​​this dispersion thread competitive pressure,

    In fact improve concurrency system of this dimension, the decentralized competitive pressure is one of the most straightforward solution.

     When implementing the java 8 ConcurrentHashMap CAS operation uses a great deal, reducing the frequency of use of locks to improve the responsiveness of the system,

     In fact, the use of locks and concurrent use CAS to do in complexity is not an order of magnitude, the use of locks is largely assumed exclusion of multiple threads,

     And the thread will block waiting for a lock, that is a lock to do thread synchronization when the state of the thread will be changed,

     But using CAS will not change a thread state (less stringent say), so the use of CAS compared to using synchronized or use it more lightweight Lcok.

 

13. If the procedures used in the thread pool, and how to perform certain actions to perform a task after it is completed?

      Java thread pool itself has provided a hook method (beforeExecute and afterExecute) before and after task execution,

      Only you need a custom thread pool inherit ThreadPoolExecutor, and then rewrite beforeExecute afterExecute method can be.

 

14. What is the synchronous / concurrent queue (wait / blocked queue)?

  

 Simple understanding is synchronous queue kept the competition synchronous reference resource threads (not stored thread), and kept the waiting queue to be awakened thread references.

   Common operations:

  

    

   Throws Exception type inserted and removed when not immediately performed, will throw an exception.

   Special Value type of insertion and removal of return a special value (true or false) in the case can not be executed immediately.

   Blocked types of insertion and removal operations at the time could not be immediately executed thread will block until the operation is when you can wake up other threads.

   Timed out type of insertion and removal operations can not be performed at the time immediately be blocked to a certain time, if not performed within the specified time, it will return a special value.

15. What is the queue synchronizer AQS, the underlying principle?

aaa

--- end --- restore content

 

0. wait / notify / notifyAll understanding?

  wait: let the thread holds the object lock wait;

  notify: wake up any thread holds the object lock;

  notifyAll: wake up all the threads holding the object lock;

  Their relationship is three, call the object's method to make a thread wait pause run by notify / notifyAll method of temporarily wait thread wakes up call.

  They are not in the method of the Thread class, but the Object class, and why?

  Because each object has a lock monitor thread to operate an object of course is to get a lock of an object, rather than a thread lock.

  important point:

  1, the call object wait, notify, notifyAll methods need a monitor lock object, i.e. they can only be used in the synchronization method (block);

  2, call the wait method uses thread pause and let the CPU resources, while releasing the lock held by the object;

  3, the use of multi-threading notify prone to deadlocks generally used notifyAll;

 

Difference 1. sleep () and wait () is?

  1.1 LIMITATIONS (exception trap)

  sleep () thread to sleep, time to proceed, we need to capture InterruptedException.

  wait () must be synchronized into a synchronization code blocks, the same need to capture InterruptedException exception and needs to acquire the lock object.

  The method also requires additional wait notify / notifyAll wakes up, they also need to be placed inside the synchronized block, and acquiring the lock object.

  notify / notifyAll do not need to catch the exception, but the wait still need to capture InterruptedException.

   1.2 usage scenarios

  typically sleep for the current thread to sleep or suspend polling operation, wait is used for communication between multiple threads.

  1.3 belongs to class

  Thread class is a static sleep native method, wait native method is the Object class.

  Why this design?

   Because sleep is for the current thread to sleep, not related to the object class, the object does not need to acquire a lock, so is the method of the Thread class.

   wait is to get the thread to achieve the object lock wait, the premise is to get the object's lock Chu, so is the method of the class.

  1.4 release lock ( the wait will release the lock, notify just notice, does not release the lock )

  wait can release the current thread holds the object lock to lock, but sleep does not.

  wait (), notify () and notifyAll () method is a local method, and a method for the final and can not be rewritten.

  The current thread must own this object's monitor (ie lock) to call an object's wait () method allows the current thread blocked.

  This blockage is synchronized by early release lock, blocking lock request to re-caused, such a request must be re-awakened by other threads compete for locks notify () or notifyAll ().

  Call an object notify () / notifyAll () method can wake up more than a / are waiting for the object monitor thread.

  notify () or notifyAll () method is not really release the lock, you must wait until the synchronized method or block executing the grammar really release the lock.

 

2. Join the use and principles?

  join () method of the Thread class Thread, definition refers to the current thread to wait after the end of the thread to continue .

  The main thread calls t.join () will block the main thread, the thread is finished until t.

  Principle: be implemented using the wait method. When the main thread calls method main thread t, the main method to get to the object lock t's,

             The t wait method calls itself by blocking whenever t the end of the time before or after exit, then wake up the main thread to continue.

 

3. Thread sleep, half-way calling thread.interrupt () What happens?

  Interrupt can interrupt sleep the current thread, and throw InterruptedException.

 

4. synchronized There are several uses?

  1. The common method of synchronization

     The same instance only one thread can acquire the lock to enter this method.

     Acts on only a single instance, multiple instances, failure of the synchronization method.

  2. Synchronize static method

     No matter how many instances of the class, only one thread can acquire the lock to enter this method.

  3. synchronization classes

    Pinning effect and synchronous static methods, are class-level locks, only one thread can access method with synchronous class lock.

  4. Examples of this synchronization

      This usage is synchronized block, lock the entire current object instance represents only get to this instance of the lock to enter this method.

     Common usage and synchronization methods lock, are locked throughout the current instance.

  The synchronization object instance XXX

  This is also the usage of sync blocks, and lock the current instance of the above, as shown here lock the entire object instance XXX, XXX only get to this instance lock to enter this method.

  important point:

  Example lock Locks are not mutually obstructive, but the same type locks, the lock current instance of the same, the same object will block lock each other.

 

The realization principle of the method of code synchronization and block synchronization?

  JVM sync block synchronization and code-based objects to enter and exit Monitor implemented method may be used monitorenter and monitorexit instructions.

  monitorenter instruction is compiled at the start position of the synchronization code is inserted into the block and is inserted into the monitorexit instruction anomaly and the method ends,

  JVM monitorenter ensure that each has a threshold value corresponding to monitorexit. Thread execution to monitorenter time, will try to get the monitor lock object corresponds,

  Before you can get access to the lock synchronize the use of Java objects stored in the header.

 

6. synchronized implementation principle?

  synchronized based Monitor (object monitors) to achieve synchronization.

  Monitor two ways to support the synchronization between threads: exclusive execution, collaboration

  1. Java using the object lock (obtained using synchronized object lock) ensure worker threads on a shared data set mutually exclusive execution.

  2. wait / notify / notifyAll method to work between the different threads.

  3. Class and Object is associated with a Monitor.

  Monitor working mechanism:

  After entering the thread synchronization method,

  In order to continue to perform critical section, a thread must acquire the lock Monitor. If you acquire a lock is successful, it will become the owner of the watcher object.

  Within any one time, the supervisor objects belong to only one active thread (The Owner).

  Who has monitored object thread can call wait () wait to enter the set (Wait Set), while monitoring the release of the lock, enter the wait state.

  After the code can execute wait after another thread calls notify () / notifyAll () interface to set the wake-up waiting threads, these threads need to wait for the monitor to reacquire lock ().

  Synchronization method is finished, the thread exits the critical region, and release the monitor lock.

 

7. The concrete realization of synchronized?

  1, the synchronization code blocks using monitorenter, monitorexit instruction explicitly implemented.

  2, the implicit synchronization method implemented ACC_SYNCHRONIZED marker used.

  monitorenter:

  Each object has a monitor, a monitor can only be a thread owns.

  When a thread attempts to execute the monitorenter instruction obtain the corresponding object monitor, access rules are as follows:

    If the number entering the monitor is 0, then the thread can enter the monitor, and the monitor is set to enter the number 1, shall monitor the thread owner.

    If the current thread already owns the monitor, only to re-enter, then enter the number into the monitor plus 1, so to achieve the synchronized keyword lock is reentrant lock.

    If the monitor has been owned by other threads, the current thread into the blocked state, until the number into the monitor to 0, and then again try to obtain monitor.

  monitorexit :

    Only those with the appropriate object monitor thread can execute monitorexit instruction.

    Each time the instruction enters monitor minus one, when released into the number of the current monitor thread is 0:00, then the blocked thread will attempt to acquire the monitor.

  Lock storage location:

  Lock mark in the Mark Word Java objects stored in the head.

  synchronized lock optimization:

  JDK1.6 introduced "biased locking" and "lightweight lock." 4 lock status: No Lock -> biased locking -> Lightweight locks -> Lock heavyweight

 

8. JMM principle of shared variables to read and write?

  Each thread has its own working memory, each thread must first share when the need for shared variables manipulated variable from main memory to load their working memory, such as when the operation is completed and then save the shared variable to main memory.

 

9. Memory invisible problem?

    If a thread is not finished brush operation to main memory, then the value of the shared variable by another thread to read from the main memory,

    This time read data is dirty data, and it overrides the other end of the calculation of the value of the thread.

 

10. volatile realization of the principle of?

  Lock prefix 1. JVM command will cause the CPU cache is written back to system memory.

  2. In order to ensure cache consistency principle, in a multi-CPU scenarios, a CPU cache write-back cache memory causes the other CPU fail, will visit again to reload a new cache content from the system memory.

 

11. HashMap is not thread safe?

    Scene 1: HashMap as local variables within the method, thread-safe!

    When local variables inside methods, local variables belonging to the current thread-level variables, other threads can not access, so security.

    Scene 2: The object member variable, unsafe!

    What are the thread-safe Map?  

    1. HashTable

        get / put methods are modified synchronized keyword, but the same thread can only get or put, low efficiency.

    2. SynchronizedMap

private Map<String, Object> map = Collections.synchronizedMap(new HashMap<String, Object>());

     The incoming synchronized HashMap packaging, implementation is to add mutex object lock, the performance is not good.

    3. ConcurrentHashMap - Recommended

       Before the lock segment JDK1.8, the tub 16 minutes, each time adding only a lock barrel.

       JDK1.8 joined CAS red-black tree algorithm and improve efficiency.

12. JDK1.7 and JDK1.8 realization of the principle of ConcurrentHashMap about?

    In java 7, the realization is achieved ConcurrentHashMap segment lock protocol based, in essence, is the use of locks.

    Just based on one consideration is that multiple threads access a hash bucket random, based on such considerations will be different hash section above, and then each segment with a lock data storage,

    The need to write a segment of the lock when needed, but at this time, other threads to access other sections of blocking is not required,

    But for this segment of threads access will have to wait until the thread releases the lock of the lock, other threads can access it. 

    In java 8 in, ConcurrentHashMap abandoned the realization of this complex architecture, but inherited the idea of ​​this dispersion thread competitive pressure,

    In fact improve concurrency system of this dimension, the decentralized competitive pressure is one of the most straightforward solution.

     When implementing the java 8 ConcurrentHashMap CAS operation uses a great deal, reducing the frequency of use of locks to improve the responsiveness of the system,

     In fact, the use of locks and concurrent use CAS to do in complexity is not an order of magnitude, the use of locks is largely assumed exclusion of multiple threads,

     And the thread will block waiting for a lock, that is a lock to do thread synchronization when the state of the thread will be changed,

     But using CAS will not change a thread state (less stringent say), so the use of CAS compared to using synchronized or use it more lightweight Lcok.

 

13. If the procedures used in the thread pool, and how to perform certain actions to perform a task after it is completed?

      Java thread pool itself has provided a hook method (beforeExecute and afterExecute) before and after task execution,

      Only you need a custom thread pool inherit ThreadPoolExecutor, and then rewrite beforeExecute afterExecute method can be.

 

14. What is the synchronous / concurrent queue (wait / blocked queue)?

  

 Simple understanding is synchronous queue kept the competition synchronous reference resource threads (not stored thread), and kept the waiting queue to be awakened thread references.

   Common operations:

  

    

   Throws Exception type inserted and removed when not immediately performed, will throw an exception.

   Special Value type of insertion and removal of return a special value (true or false) in the case can not be executed immediately.

   Blocked types of insertion and removal operations at the time could not be immediately executed thread will block until the operation is when you can wake up other threads.

   Timed out type of insertion and removal operations can not be performed at the time immediately be blocked to a certain time, if not performed within the specified time, it will return a special value.

15. What is the queue synchronizer AQS, the underlying principle?

aaa

Guess you like

Origin www.cnblogs.com/fyql/p/11334872.html