Dry: Java concurrency Programming must understand knowledge point resolution

Source: Internet
Author: User
Tags cas thread class volatile

This article outlines

Three elements of concurrent programming
    • Atomic Nature

      An atom, 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.

    • Order of

      The order in which the program executes is executed in the order of the Code. (The processor may reorder the instructions)

    • Visibility of

      When multiple threads access the same variable, if one of the threads modifies it, the other threads can get the latest value immediately.

2. The five states of the thread
    • Create State

      When creating a thread with the new operator

    • Ready state

      Calling the Start method, the thread in the ready state does not necessarily execute the Run method immediately, and waits for the CPU to dispatch

    • Running state

      The CPU starts to dispatch the thread and starts executing the Run method

    • Blocking state

      During thread execution, the blocking state is entered for some reason

      For example: Call the Sleep method, try to get a lock, etc.

    • Death status

      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

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 ways of calling wait () that must be awakened by notify or Notifyall to wake wait (long timeout) for a specified time, and if there is no wake-up of the Notify or Notifall method, it will also wake automatically. Wait (long Timeout,long Nanos) is essentially a method that calls a parameter public final void wait (long timeout, int nanos) throws Interruptedexception {I F (Timeout < 0) {throw new IllegalArgumentException ("Timeout value is negative");} if (Nanos < 0 | | Nanos > 9999 ) {throw new IllegalArgumentException ("nanosecond timeout value out of range");} if (Nanos > 0) {timeout++;} Wait (timeout);}
    • Notify

      Only one thread that is in wait can be awakened

    • Notifyall

      Wake all the threads in wait

4.2 Sleep/yield/join

This group is a method of the Thread class

  • Sleep

    Let the current thread pause for a specified time, just give up the use of the CPU and not release the lock

  • Yield

    Suspends 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. will make the current thread transition from a running state to a ready state, which is rarely used in a production environment, and is also noted by the official in its comments

    /*** a hint to the scheduler and the current thread is willing To yield* it current use of a processor. The scheduler is free to ignore this* hint.** <p> Yield are a heuristic attempt to improve relative progression* BETW Een threads that would otherwise over-utilise a CPU.  Its use* should is combined with detailed profiling and benchmarking to* ensure that it actually have the desired 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 conditions. It may also is useful when designing* concurrency control constructs such as the ones in the* {@link java.util.concurrent. Locks} package.*/
  • Join

    Wait for the thread executing to call the Join method to finish before executing the following code

    Its invocation must be after the Start method (see source)

    Usage Scenario: The Join method is used when the parent thread needs to wait for the child thread to execute the end to execute the later content or to require the execution result of a child thread

5.valitate keywords

5.1 Definitions

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, a lock prefix instruction will be more

2. It ensures that the instructions are reordered without putting the instructions behind the memory barrier, or putting the preceding instructions behind the memory barrier, that is, when the command is executed to the memory barrier, the operation in front of it is complete.

3. It forces the modification of the cache to be immediately written to main memory

4. If it is a write operation, it will cause the data in the other CPU to cache the memory address invalid

5.3 Effects

Memory visibility

multithreaded operation, a thread modifies the value of a variable, and other threads can immediately see the modified value

Prevent reordering

That is, the execution order of the program executes 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)

public class Testvalitate {public volatile int inc. = 0; public void Increase () {inc. = inc + 1;} public static void Main (S  Tring[] (args) {final testvalitate test = new Testvalitate (); for (int i = 0; i <, i++) {new Thread () {public void Run () {for (int j = 0; J < K; J + +) Test.increase ();}}. Start ();} while (Thread.activecount () > 2) {//Ensure that the previous thread finishes executing Thread.yield ();} System.out.println (Test.inc);}}
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, the lock in the implementation is divided into a biased lock, lightweight and heavyweight lock, where the bias lock in the java1.6 is the default, lightweight lock in the case of multi-threaded competition will be inflated into a heavyweight lock, the data about the lock is 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 objects are instance objects

    • modifying static methods

      The synchronization object is the class itself

    • modifying code blocks

      You can 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. Want to know the major Internet companies 2018 of the latest concurrent programming interview questions, you can add groups: 650385180, face questions and answers in the group's shared area.

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 following problems occur with synchronization

Synchronized is a pessimistic lock that can cause some performance problems in use. 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 Issues

      What is the ABA problem? For example, there is a value of type int, N is 1.

      At this point there are three threads that want to change it:

      Thread A: You want to assign N a value of 2

      Thread B: You want to assign N a value of 2

      Thread C: You want to assign N a value of 1

      At this point, thread A and thread B get to the value of N at the same time 1, thread a first get system resources, N is assigned to 2, thread B is blocked for some reason, thread C gets the current value of n after threads a executes 2

      The thread state at this time

      Thread A successfully assigns N a value of 2

      Thread B gets to the current value of N 1 and wants to assign him a value of 2, in a blocked state

      Thread C Gets the current value of good N 2 and wants to assign him a value of 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 obtained in the blocked front thread B is 1, 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 2.

      In this process, 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

      The above example is a typical ABA problem.

      How to solve the ABA problem

      Add a version number to the variable, and compare the value of the current variable to compare the version number of the current variable. Atomicstampedreference in Java solves this problem.

    • Long cycle times cost large

      In the case of high concurrency, if many threads repeatedly try to update a variable, but the update is not successful, the cycle 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.

  • Want to learn more about concurrent programming knowledge points, you can pay attention to me, I will also collate more relevant technical points to share out, in addition, by the way to recommend a communication learning Group: 650385180, which will share some senior architect recorded video recording: Spring,mybatis, Netty Source code Analysis, high concurrency, performance, distributed, micro-service architecture, JVM performance optimization These become the necessary knowledge system for architects. Also receive free learning resources and interview materials, currently benefiting a lot, the following course system map is also available in the group.

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.

Dry: Java concurrency Programming must understand knowledge point resolution

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.