"Java concurrent Programming Combat" reading notes __ algorithm

Source: Internet
Author: User
Tags closure exception handling semaphore sleep wrapper

Subsections
Thread Safety (Threads safety)
Locks (Lock)
Shared objects
Group of objects
Infrastructure building Blocks
Task execution
Cancel and close
Use of thread pools
Performance and Scalability
Test for concurrent Programs
Show lock
Atomic variables and non-blocking synchronization mechanisms

First, thread safety (threads safety)
Whenever more than one thread accesses a given state variable. And one of the threads writes the variable, you must use synchronization to assist the thread in accessing the variable. Thread safety means that when multiple threads access a class, the behavior of this class is still correct if no additional synchronization is required.      Thread-Safe instance: (1), a stateless class is thread-safe. Stateless classes are fields that do not contain any fields or that do not reference other classes. The instantaneous state of a particular calculation, which uniquely exists in the local variable.      (2), atomic operation is thread safe. A shortened form of a discrete operation to obtain the current value, add one, and write back the new value. This is a read-change-write operation and does not have atomic nature.      (3), the competitive conditions are not safe. When the correctness of the calculation depends on the Run-time-related timing or multithreading alternation, the competition condition is generated. The most common one is to check for a rerun (check-then-act). eg

public class Instance () {
     private Instance in = null;
     Public Instance getinstance () {
          if (in = = null) {
              in= new Instance ();
          }
          return in;
     }
}
This example is intended to be an object of a single instance, but if two threads execute simultaneously to getinstance (), at this point in time, in is null, depending on the timing. This is not predictable. Resolving the thread-unsafe approach caused by checking for rerun and read-write operations is the need to ensure the atomic nature of the operation. And the Java built-in atomic mechanism-locks can solve these problems.
Two, lock (lock)(1), internal Lock, Java provides the mandatory atomicity of the built-in locking mechanism: synchronized block. Complex operations that operate on shared state must be atomic to avoid competitive conditions such as read-and-write operations and check-and-run operations. A composite operation occupies a lock during the full runtime to ensure that its behavior is atomic.
third, shared objectsThe key problem in writing the correct program is that it requires proper administration when accessing the shared mutable state. (1), memory visibility we not only want to prevent a thread from accessing a state, but another thread is modifying that state at the same time. Also, when you want to make sure that a thread modifies the state of the object, other threads can see the state change that occurred. In the absence of synchronization, the compiler, the processor, makes some unexpected adjustments to the order in which the operation is performed. In the absence of a synchronized multithreaded program, it is almost impossible to get the correct conclusion about the order in which memory operations are executed.
(2), failure data in the absence of synchronization of the program to produce errors in the result of a situation is that the failure of data.
(3), lock, and visibility locks ensure that a thread can see the execution result of another thread in a predictable way, such as a code block that thread B then enters the same lock protection when a code block is executed. When B executes a lock-protected synchronized code block, you can see all the results of the operation in the same code block before thread A. Why is it necessary to synchronize a thread on the same lock when accessing a shared, mutable shared variable, to ensure that a thread writes the value of the variable to other threads. Otherwise, if a thread reads a variable without holding the correct lock, it may read a failure value.
(4), publishing and escaping
(5), thread closure when accessing shared mutable data, synchronization is usually required. One way to avoid using synchronization is to not share data. If you are accessing data only on a single agenda, you do not need to synchronize. This technique is called thread blocking. It is one of the easiest ways to thread security. Eg:jdbc Connection object, the servlet request is mostly single-threaded synchronous, and the connection pool does not assign it to other threads until the connection object returns. A more standardized way to maintain thread closure is to use threadlocal to solve the problem of resource sharing in multithreaded programming. Mention this, you will generally think of synchronized,synchronized to take the "time to change space" strategy, is essentially locked to the key resources, so that everyone queued operation. And threadlocal take the idea of "space for Time", for each thread that uses the variable to provide a separate copy of the variable, within this thread, it is equivalent to a "global variable", you can ensure that this thread at any time to manipulate the same object. Principle: Each running thread will have a map of type Threadlocal.threadlocalmap, which is used to store the variables bound to this thread, and the map key is the Threadlocal object, Value is the wrapper class entry of a variable in a task that the thread is executing.
Threadlocal has four methods:
Returns the value in the current thread copy of this thread local variable
Public T get () {
        Thread t = thread.currentthread ();
        Threadlocalmap map = getmap (t);
        if (map!= null) {
            Threadlocalmap.entry e = Map.getentry (this);
            if (e!= null) return
                (T) e.value;
        }
        return Setinitialvalue ();
    }

If this is the first call, it needs to be initialized.

Private T Setinitialvalue () {
        T value = InitialValue ();
        Thread t = thread.currentthread ();
        Threadlocalmap map = getmap (t);
        if (map!= null)
            Map.set (this, value);
        else
            createmap (t, value);
        return value;
    }
Sets the value in the current thread copy of this thread local variable to the specified value

public void Set (t value) {

        Thread t = thread.currentthread ();
        Threadlocalmap map = getmap (t);
        if (map!= null)
            Map.set (this, value);
        else
            createmap (t, value);
    

Removes the value of this thread local variable.

public void Remove () {
         Threadlocalmap m = Getmap (Thread.CurrentThread ());
         if (M!= null)
             m.remove (this);
     }
Database connection Management class, reprint: http://blog.csdn.net/ghsau/article/details/15732053

public class ConnectionManager {/** shared connection,threadlocal is generally global, supports generics */private static Threadlocal<co
     
     nnection> threadLocal = new threadlocal<connection> (); public static Connection Getcurrconnection () {//gets shared Connection Connection conn = threadlocal.g in the current thread
          ET (); try {//Determine if the connection is available if (conn = null | | conn.isclosed ()) {//Create a new Connectio
               N Assign value to conn (abbreviated)//Save Connection Threadlocal.set (conn);
     } catch (SQLException e) {//exception handling} return conn;
          /** * Closes the current database connection/public static void Close () {//Gets the shared connection within the current thread
          Connection conn = Threadlocal.get (); 
                    try {//Judge if (conn!= null &&!conn.isclosed ()) {//Shut down the resource
         Conn.close ();           Removal of connection threadlocal.remove ();
               conn = null;
 } catch (SQLException e) {//Exception handling}}}

(6), invariance to meet the synchronization requirements of another method is to use immutable objects. Immutable objects must be thread-safe. Definition of immutable object: After the object is created (by constructing the method), regardless of whether the object is non-violent (without reflection), the state of the object (the value of the instance field) will not change, and the object is immutable, and the corresponding class is the mutable class, and it does not matter if the final modification is used. When using and sharing objects in concurrent programs, you can use the policy: thread closure. Thread-closed objects can only be owned by one thread. Read-only sharing. In the absence of additional synchronization, shared read-only objects can be accessed concurrently by multiple threads. Thread sharing security. Thread-Safe objects implement synchronization within them. As a result, multiple threads can be accessed through the object's public interface without further synchronization required.
four, the object combination      (1), how to design a thread-safe class.      Designing a security class requires attention to three elements: find all the variables that construct the state of the object.      The invariant condition of the constraint state variable. Establish concurrent access management policies for object state. (2), instance closure if an object is not thread-safe, we can use a variety of techniques to make it safe in multiple threads. Make sure that the object is accessible only by a single thread.

public class personset{
          private final set<person> MySet = new hashset<person> ();
          
          Public sychronized void Addpersion (person p) {
               myset.add (p)
          } public
     
          sychronized Boolean Containsperson ( Person P] {return
               myset.contains (p);
          }
     }
Although HashSet is not thread-safe. But MySet is private and does not escape. The only code that can access MySet is Addperson (), and Containsperson (). The lock on the personset that they all want to get on the execution. The Personset state is completely protected by its built-in lock. So Personset is a thread-safe class. The Java Platform's class library has examples of closed instances. For example, some basic containers are not thread-safe, such as Arraylist,hashmap. The wrapper method provided by the class library, collections.synchronizedlist (list), Collections.synchronizedmap (m) makes it possible for a class that is not thread-safe to be used in multiple threads. (3) The Java Monitor mode encapsulates all the mutable states of an object and is protected by its own internal locks.
public class Privatelock {
          private final Object MyLock = new Object ();
     
          private int weight;
          
          void SomeMethod () {
               synchronized (myLock) {
                    //Access Weight
               }
     }}
Using private lock objects has many advantages over built-in locks that use objects. A private lock encapsulates the lock, and the client code cannot get a lock. However, the client can access the lock through a public method. To participate in the synchronization strategy.
A monitor is like a building, it has a very special room, the room has some data, and at the same time can only be occupied by a thread, into the building called "Access Monitor", into the building of the special room called "Access Monitor", occupy the room is called "holding Monitor", leaving the room called " Release Monitor ", leaving the building is called" Exit Monitor ".
As shown in the figure above, a thread enters the entry Set (entry area) through Gate 1th, and if there is no thread waiting in the entry area, the thread acquires the monitor as owner of the monitor and executes the code for the monitoring area. If there are other threads waiting in the entry area, the new threads will also wait with the threads. Threads in the process of holding a monitor, there are two choices, one is the normal execution of the monitor area code, release the Monitor, through Gate 5th exit the monitor, and may wait for a certain condition, so it will pass gate 3rd to wait Set (waiting area) rest, Until the corresponding conditions are met and then go through gate 4th to regain the monitor and then execute.
Note: When a thread releases the monitor, the waiting thread in the entry area and the waiting area will go to the competition monitor, and if the entry area's thread wins, it will enter from gate 2nd, and if the waiting area's thread wins, it will enter from gate 4th. Only through gate 3rd to enter the waiting area, the thread in the waiting area can only exit the waiting area through gate 4th, which means that a thread can only perform a wait operation while holding the monitor, and that the waiting thread can only get the monitor again before exiting the wait state.
v. Basic building Blocks(1), Synchronization container class. including vectors and Hashtable.      The encapsulated container class that is synchronized is created by the Collections.sychronizedxxx factory method.      Eg:synchronizedlist,synchronizedmap (M), Synchronizedset (s) (2), Synchronization tool class. Blocking queues (Blockingqueue (linkedblockingqueue,arrayblockingqueue,priorityblockingqueue,synchronousqueue)) not only save the object's container,      It can also coordinate the flow of control between producers and consumers. Semaphore (semaphore): The number of operations that are used to control access to a particular resource at the same time. Obtain a license by acquire (), and if not, wait, and release () releases a license. Semaphore allows a thread to obtain a license, and an unlicensed thread waits. This prevents too many threads from executing at the same time. Semaphore realize the function is similar to the toilet has 5 pits, if there are 10 people to go to the toilet, then can only have how many people to the toilet. At the same time only 5 people can occupy, when one of the 5 people out of the way, the other 5 waiting for another person can occupy. The other 5 people waiting for them can be randomly given priority, or get an opportunity in arrival order, depending on the parameter options that are passed in when the semaphore object is constructed.  The semaphore object of a single semaphore can implement a mutex function, and it can be "locked" by one thread and released by another thread, which can be applied to some situations of deadlock recovery. Eg: simulate 30 vehicles to park the car, and the parking space has 10 scenes. When the parking space is full, a car comes out to get a car into the parking lot. Reprint http://mouselearnjava.iteye.com/blog/1921468
Package My.concurrent.semaphore;

Import Java.util.concurrent.Semaphore;

     public class car implements Runnable {private final semaphore parkingslot;

     private int Carno;
          /** * @param parkingslot * @param carname/public car (semaphore parkingslot, int carno) {
          This.parkingslot = Parkingslot;
     This.carno = Carno;
               public void Run () {try {parkingslot.acquire ();
               Parking ();
               Sleep (300);
               Parkingslot.release ();

          Leaving ();
          catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
     } private void Parking () {System.out.println (String.Format ("%d cars parked", Carno));
     private void Leaving () {System.out.println (String.Format ("%d car left Parking", Carno));
       private static void sleep (long Millis) {try {        Thread.Sleep (Millis);

          catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();

}} package My.concurrent.semaphore;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Semaphore;

     public class Parkingcars {private static final int number_of_cars = 30;

     private static final int number_of_parking_slot = 10; public static void Main (string[] args) {/* * using FIFO, set true/semaphore parking

          Slot = new Semaphore (Number_of_parking_slot, true);

          Executorservice service = Executors.newcachedthreadpool ();
          for (int carno = 1; carno <= number_of_cars; carno++) {Service.execute (New car (Parkingslot, Carno));

          Sleep (3000);

          Service.shutdown (); * * * Output also has several available resources/System.Out.println (parkingslot.availablepermits () + "A parking space can be used!");
          private static void sleep (long Millis) {try {thread.sleep (Millis);
          catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
 }
     }

}

Operation Result: Car No. 1th Parking
Car Parking No. 4th
Car Parking No. 9th
Car Parking No. 2nd
Car Parking No. 8th
Car Parking No. 10th
Car Parking No. 3rd
Car Parking No. 12th
Car Parking No. 14th
Car Parking No. 6th
Car number 2nd out of the parking space.
Car number 4th out of the parking space.
Car number 6th out of the parking space.
Car number 1th out of the parking space.
Car number 9th out of the parking space.
Car number 3rd out of the parking space.
Car Parking No. 5th
Car number 8th out of the parking space.
Car number 10th out of the parking space.
Car Parking No. 11th
Car Parking No. 7th
Car number 12th out of the parking space.
Car Parking No. 13th
Car number 14th out of the parking space.
Car Parking No. 16th
Car Parking No. 17th
Car Parking No. 20th
Car Parking No. 19th
Car Parking No. 18th
Car Parking No. 15th
Car number 5th out of the parking space.
Car number 20th out of the parking space.
Car number 18th out of the parking space.
Car Parking No. 22nd
Car number 11th out of the parking space.
Car number 7th out of the parking space.
Car number 13th out of the parking space.
Car number 15th out of the parking space.
Car Parking No. 21st
Car Parking No. 26th
Car Parking No. 23rd
Car Parking No. 28th
Car Parking No. 25th
Car number 16th out of the parking space.
Car Parking No. 27th
Car number 17th out of the parking space.
Car Parking No. 30th
Car Parking No. 24th
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.