Java Concurrency Programming

Source: Internet
Author: User
Tags cas thread class visibility volatile

Java concurrency Programming, you need to know.

Three elements of concurrent programming
    • An atom of atoms, a particle that cannot be split again. In Java, the sub-nature refers to one or more operations that either execute successfully or all fail.
    • The order in which the ordered program executes is executed in the order of the Code. (The processor may reorder the instructions)
    • visibility When multiple threads access the same variable, if one of the threads modifies it, other threads can immediately get to the latest value.
2. The five states of the thread
    • Create a State when creating a thread with the new operator
    • The ready state calls the Start method, and the thread in the ready state does not necessarily execute the Run method immediately, but also waits for the CPU to dispatch
    • Running State The CPU starts to dispatch the thread and starts executing the Run method
    • blocking states during execution of a thread for a number of reasons such as: Call the Sleep method, try to get a lock, etc.
    • Death State The Run method finishes executing or encounters an exception during execution
3. Pessimistic lock and optimistic lock
    • pessimistic lock : Each operation will be locked, causing the thread to block.
    • optimistic lock : each time the operation is not locked but assumes that there is no conflict to complete an operation, if the conflict failed to retry, until successful, will not cause the thread to block.
4. Collaboration between Threads 4.1 Wait/notify/notifyall

This group is a method of the Object class and it is important to note that all three methods must be called within a synchronized range

    • Wait blocks the current thread until notify or Notifyall wakes up
  Wait has three different ways of callingWait()Must be awakened by notify or Notifyall.Wait(LongTimeout)If there is no wake-up of the Notify or Notifall method, it will automatically wake up within the specified time.Wait(LongTimeout,LongNanos)Essentially, a method that invokes a parameterPublicFinalvoidWait(LongTimeout,IntNanos)ThrowsInterruptedexception{If(Timeout<0){ThrowNewIllegalArgumentException("Timeout value is negative" if  (nanos < | | nanos > 999999) { throw new illegalargumentexception (  "nanosecond timeout value out of range" );  if  (nanos > ) {timeout++; } wait (timeout              /span>                
    • Notify can only wake up a thread that is in wait
    • Notifyall Wake all the threads in wait?
4.2 Sleep/yield/join

This group is a method of the Thread class

    • Sleep lets the current thread pause for a specified time, just gives up the use of the CPU and does not release the lock

    • Yield pauses the execution of the current thread, which is the current CPU's right to use, giving other threads the opportunity to execute and not specify a time. Causes the current thread to transition from a running state to a ready state, which is rarely used in a production environment, and is also described by the official in its comments

  /** * A hint to the scheduler that the Curren T thread is the willing to yield * it current use of a processor.        The scheduler is a free-to-ignore this * hint. * * <p> Yield is a heuristic attempt to improve relative progression * between threads that would othe Rwise over-utilise a CPU. Its use * should is combined with detailed profiling and benchmarking to * ensure that it actually have the D        Esired effect. * * <p> It is rarely appropriate to use the This method. It may is useful * for debugging or testing purposes, where it could help to reproduce * bugs due to race cond Itions. It may also is useful when designing * concurrency control constructs such as the ones in the * {@link java.        Util.concurrent.locks} package. */
    • Join waits for the thread that calls the join method to execute the end before executing the code whose invocation must be followed by the Start method (see Source) Usage scenario: When the parent thread needs to wait for the child thread to execute the end before executing the content or the execution result of a child thread is required to use the Join method
5.valitate Keyword 5.1 definition

The Java programming language allows threads to access shared variables, and in order to ensure that shared variables can be updated accurately and consistently, the thread should ensure that the variable is obtained separately through an exclusive lock. The Java language provides volatile, which in some cases is more convenient than a lock. If a field is declared as a Volatile,java thread, the memory model ensures that all threads see that the value of this variable is consistent.

Valitate is a lightweight synchronized that does not cause thread context switching and scheduling, and is less expensive to execute.

5.2 Principle

1. Variables modified with volitate in the assembly phase, there will be a lock prefix directive 2. It ensures that instructions are reordered without putting the instructions behind them into place before the memory barrier, and not putting the preceding instructions behind the memory barrier ; that is, when executing to the memory barrier, the operation in front of it has all completed 3. It forces the modification of the cache to be immediately written to main memory 4. If it is a write operation, it causes the data in the other CPU to cache the memory address invalid

5.3 Effects

Memory Visibility when multithreaded, a thread modifies the value of a variable, and other threads immediately see the modified value preventing the reordering of the execution order of the program in the Order of the Code (the processor may reorder the code in order to improve the execution efficiency of the Code)

There is no guarantee that the atomic nature of the operation (such as the following code execution result must not be 100000)

    PublicClassTestvalitate{PublicVolatileIntInc=0;PublicvoidIncrease(){Inc=Inc+1;}PublicStaticvoidMain(String[]Args){FinalTestvalitateTest=NewTestvalitate();For(IntI=0;I<100;I++){NewThread(){PublicvoidRun(){For(IntJ=0;J<1000;J++)test. (); } . start ();  while  (thread. Activecount () > 2 {//ensure that all previous threads are executed thread. (); } system.. (test. Inc} }             /span>                
6. Synchronized keyword

Ensure thread-mutually exclusive access synchronization code

6.1 Definitions

Synchronized is a type of lock implemented by the JVM, where the acquisition and release of Locks are monitorenter and monitorexit instructions, which are divided into biased, lightweight, and heavyweight locks in implementation, where the bias lock is turned on by default in java1.6, Lightweight locks are inflated into heavyweight locks in the case of multi-threaded competition, and data about locks are stored in the object header

6.2 Principle

Add the Synchronized keyword to the code snippet, the resulting bytecode file will be more than Monitorenter and monitorexit two instructions (using Javap-verbose bytecode file can be seen off, the document about these two instructions are as follows:

  • Monitorenter  each object is associated with a monitor. A Monitor is locked if and only if it have an owner. The thread that executes Monitorenter attempts to gain ownership of the monitor associated with ObjectRef, as follows:? If the entry count of the monitor associated with ObjectRef are zero, the thread enters the monitor and sets its entry Coun T to one. The thread is then the owner of the Monitor. ? If the thread already owns the monitor associated with ObjectRef, it reenters the monitor, and incrementing its entry count. ? If Another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is Zero, then tries again to gain ownership.
  • Monitorexit The thread that executes Monitorexit must is the owner of the monitor associated with the instance referenced by ObjectRef . The thread decrements the entry count of the monitor associated with ObjectRef. If as a result the value of the entry count is zero, the thread exits the monitor and are no longer its owner. Other threads, that is blocking to enter the monitor is allowed to attempt.

Add the Synchronized keyword method, the generated bytecode file will be more than one acc_synchronized flag bit, when the method call, the calling instruction will check the method's acc_synchronized access flag is set, if set, The execution thread will get the monitor first, and then the method body can be executed before releasing monitor after the method is executed. No other thread can get the same monitor object during the execution of the method. In fact, there is no difference, but the method of synchronization is an implicit way to achieve, without the bytecode to complete.

6.3 about using
    • Modifying a common method synchronization object is an instance object
    • Modifying a static method The synchronization object is the class itself
    • Modifying a code block to set the synchronization object yourself
6.4 Disadvantages

Will let the non-lock resources into the block state, contention for resources and then into the running state, the process involves operating system user mode and kernel mode switching, the cost is relatively high. The Java1.6 has been optimized for synchronized, increasing the excess from biased locks to lightweight locks to heavyweight locks, but the performance is still low after the final transition to a heavyweight lock.

7. CAS

Atomicboolean,atomicinteger,atomiclong and Lock related classes, such as the underlying is the implementation of CAS, to a certain extent, higher performance than synchronized.

7.1 What is CAs

CAS full name is compare and Swap, which is a technique to implement concurrency by comparing substitution. The operation consists of three operands-the memory location (V), the expected original value (A), and the new value (B). If the value of the memory location matches the expected original value, the processor automatically updates the location value to the new value. Otherwise, the processor does nothing.

7.2 Why there are CAs

If you only use synchronized to ensure that the synchronization of the following problems synchronized is a pessimistic lock, in use will cause a certain performance problems. In the multi-threaded competition, locking, releasing locks can cause a lot of context switching and scheduling delay, causing performance problems. Holding a lock on one thread causes all other threads that require this lock to hang.

7.3 Implementation Principle

Java does not have direct access to the underlying operating system, and is accessed through the native method (JNI). The CAs bottom layer implements atomic operations through unsafe classes.

7.4 Problems that exist
    • ABA question what is ABA problem? For example there is a value of int type N is 1 at this point there are three threads that want to change it: Thread A: Want to assign N to 2 thread B: I want to assign N to 2 thread C: I want to assign n a value of 1, and thread A and thread B get the value of n at the same time, thread A takes the system resource The assignment is 2, thread B is blocked for some reason, thread C gets the current value of n after threads a finishes execution 2 at this time thread state thread A succeeds to n assignment to 2 thread B gets to n the current value 1 want to give him a value of 2, in the blocking state thread C get the current value of good N 2 want to give him a value is 1? Then thread c succeeds in assigning n a value of 1, finally thread B gets the system resources, and then resumes the running state, the value of n is 1 in the blocked front thread B, and the compare operation finds that the value of the current n is the same as the value obtained (both 1), and succeeds in assigning N to the value 2. In this process, the thread B gets to the value of n is an old value, although equal to the current value of N, but actually the value of n has undergone a change of 1 to 2 to 1 above This example is the typical ABA problem how to solve the ABA problem to add a version number to the variable, Comparing the values of the current variable, you need to compare the version number of the current variable. Atomicstampedreference in Java solves this problem.
    • Long cycle time overhead in the case of high concurrency, if many threads repeatedly try to update a variable, but the update is not successful, the loop will bring a lot of pressure on the CPU.

CAs can only guarantee atomic manipulation of a shared variable

8. Abstractqueuedsynchronizer (AQS)

Aqs, an abstract queue synchronizer, is a state-based list management method. State is modified with CAs. It is the most important cornerstone of the Java.util.concurrent package, and learning to learn the contents of the Java.util.concurrent package is key. The principle of Reentrantlock, Countdownlatcher and Semaphore is based on Aqs. Want to know how he achieved and how to implement the principle can see this article https://www.cnblogs.com/waterystone/p/4920797.html

9. Future

In concurrent programming we generally use runable to perform asynchronous tasks, but we do not get the return value of the asynchronous task, but we can use the future. Using the future is simple, just change the runable to Futuretask. The use of the relatively simple, there is not much to do introduction.

10. Thread pool

If we use threads to create a thread, though it is simple, there are a lot of problems. If the number of concurrent threads is large, and each thread is executing a short task, then the frequent creation of threads can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently. The thread pool is reused to greatly reduce the performance loss caused by the frequent creation and destruction of threads.

Java thread pool Implementation class Threadpoolexecutor, the meaning of each parameter of its constructor is already written clearly in the comments, here are a few key parameters can be said briefly

    • Corepoolsize: The number of core threads retains the number of threads in the thread pool, and is not destroyed even if it is idle. To set Allowcorethreadtimeout to true, it will be destroyed.
    • Maximumpoolsize: Maximum number of threads allowed in a thread pool
    • KeepAliveTime: The maximum idle time allowed by non-core threads is destroyed locally over this time.
    • WorkQueue: The queue used to hold the task.
      • Synchronousqueue: This queue will allow the newly added task to be executed immediately, and if all threads in the thread pool are executing, then a new thread will be created to perform the task. When using this queue, maximumpoolsizes generally sets a maximum value Integer.max_value
      • Linkedblockingqueue: This queue is a unbounded queue. How to understand, is how many tasks we will execute how many tasks, if the thread pool thread is less than corepoolsize, we will create a new thread to perform this task, if the number of threads in the thread pool equals corepoolsize, the task will be placed in the queue waiting, Because the queue size is not limited, it is also called a unbounded queue. Maximumpoolsizes does not take effect when using this queue (thread pool threads will not exceed corepoolsize), so it is generally set to 0.
      • Arrayblockingqueue: This queue is a bounded queue. You can set the maximum capacity of a queue. When the thread pool is greater than or equal to maximumpoolsizes, the task is placed in this queue, and when the task in the current queue is greater than the maximum capacity of the queue, the task is discarded by rejectedexecutionhandler processing.

Finally, this article mainly on the Java concurrency Programming development needs of the knowledge point made a simple explanation, here every knowledge point can be explained with an article, because of space reasons can not be detailed on every knowledge point, I believe that through this article you will have a closer look at Java concurrency programming. If you find that there are gaps or errors, you can add them in the comments section, thank you.

Java Concurrency Programming

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.