Summarization and consideration of Java concurrent Programming __ algorithm

Source: Internet
Author: User
Tags finally block volatile java web

Writing high quality concurrent code is a very difficult thing to do. The Java language has built up the support for multithreading from the first version, which was remarkable at the time, but when we had a deeper understanding of concurrent programming and more practice, there were more schemes and better choices for concurrent programming. This article is a summary of concurrent programming and thinking, but also share the Java 5 later version of how to write the concurrency code a little experience. Why do I need concurrent

Concurrency is actually a decoupling strategy that helps us to separate what we do (the goals) and when we do it. Doing so can significantly improve the throughput of the application (get more CPU scheduling time) and structure (the program has several parts working together). As anyone who has done Java web Development knows, the servlet program in the Java Web has a single instance of multithreaded working mode supported by the servlet container, and the servlet container handles concurrency problems for you. misunderstanding and positive solutions

The most common misconceptions about concurrent programming are as follows:

-Concurrency always improves performance (concurrency can significantly improve the performance of the program when the CPU has a lot of idle time, but when the number of threads is high, frequent scheduling switching between threads can degrade the performance of the system)
-Writing concurrent programs without modifying the original design (the decoupling of purpose and timing often has a huge impact on the structure of the system)
-Do not focus on concurrent issues when using Web or EJB containers (only understand what the container is doing to better use the container)

The following statements are the objective understanding of concurrency:

-Writing concurrent programs adds extra overhead to your code
-The right concurrency is very complex, even for very simple questions
-Defects in concurrency because they are not easy to reproduce and are not easily detected.
-concurrency often requires a fundamental change in design strategy, the principle of concurrent programming and the principle of single responsibility

Detach concurrency related code and other code (concurrency related code has its own development, modification, and tuning lifecycle). Restricting data scopes

Two threads may interfere with each other when modifying the same field of a shared object, causing unpredictable behavior, one of which is to construct a critical section, but the number of critical areas must be restricted. working with Data replicas

A copy of a data is a good way to avoid sharing data, and the copied objects are treated only in a read-only manner. Java A class named Copyonwritearraylist is added to the Java.util.concurrent package in 5, which is a subtype of the list interface, so you can think of it as a ArrayList thread-safe version that uses a write-time copy to create a copy of the data to avoid the shared number A problem that is caused by concurrent access. threads should be as independent as possible

Let threads exist in their own world and do not share data with other threads. As anyone with experience in Java Web Development knows, a servlet works in single instance multithreading, and each request-related data is passed through the Servlet subclass's service method (or Doget or Dopost method) parameters. The servlet does not cause synchronization problems as long as the code in the servlet uses only local variables. The controller of Spring MVC did the same, and the objects obtained from the request were passed in as a parameter to the method rather than as members of the class, and it was clear that Struts 2 was the opposite, so the action class as a controller in Struts 2 was an instance of each request. concurrent programming prior to Java 5

The Java threading model is based on preemptive thread scheduling, which means that all threads can easily share objects in the same process. Any thread that can reference these objects can modify them. In order to protect the data, the object can be locked.

Java thread-and-lock concurrency is too low-level, and the use of locks can be very heinous in many cases, because it is tantamount to making all of the concurrency into queues. &NBSP
before Java 5, the function of a lock can be implemented using the Synchronized keyword, which can be used in blocks and methods of code to indicate that the thread must acquire the appropriate lock before executing the entire block or method of code. For a non-static method of a Class (member method), this means that to get the lock on an object instance, for the static method (class method) of the class, to get the lock of the class object, for the synchronized code block, the programmer can specify the lock to be obtained for that object. &NBSP
Whether it is a synchronized code block or a synchronous method, only one thread can enter at a time, and if other threads attempt to enter (whether the same synchronized block or a different synchronized block), the JVM suspends them (into the lock pool). This structure is called the Critical Region (critical section) in the Concurrency theory. Here we can make a summary of the function of using synchronized to implement synchronization and lock in Java: Only the object can be locked, the single object in the array of objects whose base data type is locked cannot be locked. The synchronized method may be considered to contain the entire method synchronized (this) { ... } A code block static synchronization method locks the synchronization of the class object's internal classes with the synchronized modifier independent of the external class is not part of the method signature, so the unsynchronized methods that cannot appear in the method declaration of the interface do not care about the state of the lock, and they can still be run while the synchronization method is running The lock implemented by synchronized is a reentrant lock.

Within the JVM, for efficiency, each thread running at the same time has a cached copy of the data it is working on, and when we synchronize using Synchronzied, the real synchronization is the memory block that represents the locked object in a different thread (the replica data is kept synchronized with the main memory, Now you know why you need to sync this vocabulary. Simply put, after the synchronization block or synchronization method is executed, any modifications made to the locked object are written back to the main memory before releasing the lock, and the data of the locked object is read from the main memory after the lock is entered into the synchronized block. The data copy of the thread holding the lock must be synchronized with the data view in the main memory.
In the initial version of Java, there is a keyword called volatile, which is a simple process of synchronization, because variables modified by volatile follow the following rules: The value of a variable is always read from the main memory before it is used. Changes to the value of a variable are always written back to the main memory after completion.

Use the volatile keyword to prevent compiler incorrect optimization assumptions in a multithreaded environment (the compiler may optimize variables that do not change values in one thread to constants). However, only variables that are not dependent on the current state (the value of the read) should be declared as volatile variables when modified.
Invariant mode is also a design that can be considered when concurrent programming. The state of the object is invariant, and if you want to modify the state of the object, a copy of the object is created and the changes are written to the copy without changing the original object, so that the invariant object is thread safe. In Java we use the very high frequency string class to use this design. If you are unfamiliar with the invariant pattern, you can read the 34th chapter of Dr. Shanhong's Java and schema book. Speaking of which, you may also realize the significance of the final keyword. concurrent Programming in Java 5

Regardless of the direction of future Java development or out of the busy, Java 5 is definitely a very important version of Java development history, this version provides a variety of language features we are not here to discuss (interested can read my another article " 20th year of Java: Evolution from the Java version to the development of programming technology), but we have to thank Doug Lea in Java 5 provides his landmark masterpiece Java.util.concurrent package, which makes Java concurrent programming more choice and better way to work. Doug Lea's masterpiece consists mainly of the following: better thread-safe container thread pool and associated tool class optional non-blocking solution display lock and semaphore mechanism

Here's a one by one reading of these things. Atomic Class

The Java.util.concurrent package in Java 5 has a atomic child package with several classes that begin with atomic, such as Atomicinteger and Atomiclong. They take advantage of the characteristics of modern processors and can do atomic operations in a non-blocking manner, as shown in the following code:

/**
 ID Sequence Generator
*
/public class Idgenerator {
    private final atomiclong sequencenumber = new Atomiclong (0); C4/>public long Next () {return
        sequencenumber.getandincrement (); 
    }
}
   
   
    
    1
    
    2
    
    3
    
    4
    
    5
    
    6
    
    7 8 9 Ten 1 2 3 4 5 6
    
    7
    
    8
    
    9
    
    10
   
   
Show Lock

The locking mechanism based on the Synchronized keyword has the following problems: The lock has only one type and is the same for all synchronization operations The lock can only be obtained at the beginning of the code block or method, releasing the thread at the end of the lock, or blocking, no other possibility

Java 5 reconstructs The lock mechanism, provides a display of locks that can be promoted in several ways: you can add different types of locks, such as reading locks and write locks that can be locked in one method, and unlocking in another method can use Trylock to try to acquire a lock, if a lock can wait, Rewind or do something else, and of course you can abort the operation after the timeout.

The display of the lock implements the Java.util.concurrent.Lock interface, there are two main implementation classes: Reentrantlock-slightly more flexible than the synchronized lock Reentrantreadwritelock- A reentrant lock that performs better when a lot of writing is done in a read operation

For how to use a display lock, refer to the code for question 60th in my Java interview series, "Java Face Test set 51-70". There is only one point to be reminded, the method of unlocking the unlock is best to be in the finally block, because this is the best place to release the external resources and, of course, the best place to release the lock, because the normal exception may have to release the lock to give the other thread the chance to run. Countdownlatch

Countdownlatch is a simple synchronization mode that allows one thread to wait for one or more threads to do their work to avoid problems caused by concurrent access to critical resources. Let's take a piece of code from someone else (I did some refactoring on it) to demonstrate how Countdownlatch works.

Import Java.util.concurrent.CountDownLatch;        /** * Worker class * @author Shanhao * * */class Worker {private String name;  Name Private long workduration;
        Work Duration/** * constructor/public Worker (String name, long workduration) {this.name = name;
    This.workduration = workduration;
        /** * Complete work */public void DoWork () {System.out.println (name + "begins to work ..."); try {thread.sleep (workduration);//////////(Interruptedexception ex) {ex.
        Printstacktrace ();
    } System.out.println (name + "has finished the job ...");
    }/** * Test thread * @author Shanhao * */class Workertestthread implements Runnable {private worker worker;

    Private Countdownlatch Cdlatch;
        Public Workertestthread (worker worker, Countdownlatch cdlatch) {this.worker = worker;
    This.cdlatch = Cdlatch; @Override public void Run () {worker. DoWork ();    Let the workers start work cdlatch.countdown ();  After the completion of the countdown to reduce the number of times 1}} class Countdownlatchtest {private static final int max_work_duration = 5000;  Maximum working time private static final int min_work_duration = 1000; Minimum working time//generating random working time private static long getrandomworkduration (long, long Max) {return (long) (Mat
    H.random () * (max-min) + min);   public static void Main (string[] args) {Countdownlatch latch = new Countdownlatch (2);
        Create a countdown latch and specify a countdown number of 2 worker w1 = new Worker ("Shanhao", Getrandomworkduration (Min_work_duration, max_work_duration));

        Worker W2 = new Worker ("King Hammer", Getrandomworkduration (Min_work_duration, max_work_duration));
        New Thread (New Workertestthread (W1, latch)). Start ();

        New Thread (New Workertestthread (W2, Latch)). Start ();  try {latch.await ();
        Wait for the countdown latch to be reduced to 0 System.out.println ("All jobs have been finished!"); catch (Interruptedexception E) {e.printstacktrace ();
    
    }} 1 2 3 4 5 6 7 8 9
    
    10 11 12 13 14 15 16 17 18 19
    
    20 21 22 23 24 25 26 27 28 29 
    
    30 31 32 33 34 35 36 37 38 39 40
    
    41 42 43 44 45 46 47 48 49 50
    
    51 52 53 54 55 56 57 58 59 60
    
    61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 1 2 3 4 5 6 7 8
    
     9

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.