Thread Implementation Async

Source: Internet
Author: User
Tags volatile

  

, he "sync" is not this "sync"--we say that the shared data synchronization in Java (synchronized)
, he "sync" is not this "sync"--we say that the shared data synchronization in Java (synchronized)

For each request, host generates a thread that is responsible for generating the "cake" that the customer needs. After waiting for some time, if the cake is not ready, the customer must wait. Until "Cake is done", namely Future.setrealdata (Realdata); After the execution, the customer can take the cake.

Each thread is solely responsible for making the "cake" required for a particular customer. That is, customer a corresponds to cake master A, customer B corresponds to cake Master B. Even if customer B's cake is done first, customer a can only wait for cake master A To do the cake well. In other words, there is no competitive relationship between customers.

Java thread synchronization vs. asynchronous thread pool 1) When multiple threads concurrently request the same resource, it is inevitable that the data of this resource is unsafe, a thread modifies the processing data of the B thread, and the B thread modifies the math of the a thread processing. Obviously this is due to global resources, and sometimes in order to solve this problem, it is preferable to use local variables

Java thread synchronization vs. asynchronous thread pool 1) When multiple threads concurrently request the same resource, it is inevitable that the data of this resource is unsafe, a thread modifies the processing data of the B thread, and the B thread modifies the math of the a thread processing. Obviously this is due to global resources, and sometimes in order to solve this problem, prioritize the use of local variables, fallback to use synchronous code block, for such security considerations must sacrifice the system processing performance, add in multi-threaded concurrency when the most intense resources in the place, This realizes the synchronization mechanism of the thread synchronization: a thread to request a resource, but this resource is being used by the B thread, because the synchronization mechanism exists, a thread is not requested, what to do, a thread can only wait for the asynchronous: a thread to request a resource, but this resource is being used by the B thread, because there is no synchronization mechanism exists , a thread is still requested, a thread does not have to wait

Obviously, synchronization is the safest and most insured. and asynchronous insecure, easy to lead to deadlock, so that a thread dead will cause the entire process to crash, but there is no synchronization mechanism exists, performance will be improved


Thread pooling it is necessary to know that any resource creation, including threads, in a computer consumes system resources. In a Web service, the response to the Web server must be as fast as possible, and it is not necessary to create a thread service every time the user submits the request button. In order to reduce the waiting time of the user, the thread must be pre-created, put in the threads pool, and the thread pool can be implemented with Hashtable data structure, see the source code of Apach HTTP server's thread pool, use is hashtable,key with thread object, value Using controlrunnable,controlrunnable is the only thread in the thread pool that can work, and is the thread that it assigns to the thread pool to serve. For security reasons, the thread pool of the Apach HTTP server is synchronized. I heard that WebLogic has asynchronous implementation, not studied, not sure


Keywords: thread (thread), Thread-safe (thread safe), intercurrent (concurrent) synchronized (synchronous), asynchronized (asynchronous), volatile (variable), Atomic (atomic), Share (shared)


Three, the concept: 1, when must be synchronized? What does synchronization mean? How do I sync? To maintain correct visibility across threads, you must use synchronized (or volatile) to ensure that one thread can see changes made by another thread as long as the non-final variable is shared between several threads. Synchronization is necessary for reliable communication between threads and for mutually exclusive access. This is due to the Java language Specification's memory model, which specifies when and how changes made by one thread become visible to other threads. Because multithreading introduces asynchronous behavior into a program, there must be a way to enforce it when synchronization is required. For example, if 2 threads want to communicate and want to share a complex data structure, such as a linked list, you need to ensure that they do not conflict, that is, the B thread must be prevented from writing data to the linked list while the A thread is reading the data (a gets the lock, B must wait for a to release the lock). To achieve this, Java implements an ingenious scheme based on an old process synchronization model, monitor, which is a control mechanism that can be thought of as a small box that can hold only one thread, and once a thread enters the monitor, the other threads must wait. Until the thread exits monitoring. In this way, a monitor can guarantee that a shared resource can only be used by one thread at a time. This approach is called synchronization. (Once a thread enters any synchronization method for an instance, the other thread will not be able to enter another synchronization method for that same instance, but the instance's non-synchronous method can still be called). Wrong understanding: synchronization, just a few threads can be accessed at the same time. Synchronous and multi-threaded relationships: No synchronization is required without multithreaded environments, and a multi-threaded environment does not necessarily require synchronization. The lock provides two main features: Mutual exclusion (mutual exclusion) and visibility (visibility). Mutual exclusion allows only one thread to hold a particular lock at a time, so you can use this attribute to implement a coordinated access protocol to shared data so that only one thread can use that shared data at a time. Visibility is more complex, and it must ensure that the changes made to the shared data before the lock is released are visible to the other thread that subsequently acquired the lock-if there is no such visibility guaranteed by the synchronization mechanism, the shared variables that the thread sees may be pre-modified or inconsistent values. This will lead to a summary of many serious problems: in order to prevent multiple threads from concurrently modifying the same data, synchronization is required, otherwise the data will be inconsistent (what is known as thread safety). As in the Java Collection framework, hashtable and vectors are thread-safe. Most of our programs are not thread-safe because there is no synchronization and we do not need to, because most of the cases do not have a multi-threaded environment at all. 2, what is called Atomic (atomic operation)? The Java atomic operation means: NoThe operation was interrupted. (Is mutual exclusion and visibility?!) Is it true that atomic manipulation can actually achieve a thread-safe synchronization effect? There are actually some atomic operations that are not necessarily thread-safe. So, under what circumstances are atomic operations not thread-safe? This may be the cause: The Java thread allows the thread to save a copy of the variable in its own memory area. Allowing a thread to work with a local private copy instead of using the value of main memory every time is to improve performance (I humble opinion: Although the atomic operation is thread-safe, each thread can play its own copy after the variable (read operation) is obtained, the update operation (write operation) is not written to the main store, causing other threads not to be visible). So how do we fix it? Therefore, the Java synchronization mechanism is required. In Java, the assignment of 32-bit or fewer digits is atomic. On a 32-bit hardware platform, other primitive types except double and long are usually represented using 32 bits, whereas double and long are usually represented by 64 bits. In addition, object references are implemented using native pointers and are typically 32-bit. Operations on these 32-bit types are atomic. These primitive types are usually represented by 32-bit or 64-bit, which introduces another small myth: the size of the original type is guaranteed by the language. That's not right. The Java language guarantees that the range of tables in the original type is not the size of the storage in the JVM. Therefore, the int type always has the same number of table ranges. A 32-bit implementation may be used on one JVM, and possibly 64 bits on another JVM. Again, it is emphasized that the range of tables is guaranteed on all platforms, and the operation of 32-bit and smaller values is atomic. 3, do not confuse: synchronous, asynchronous for example: ordinary B/s mode (synchronous) Ajax Technology (asynchronous) synchronization: Submit request, wait for server processing, and then return to the client browser can not do anything asynchronous: request through Event Trigger Server processing (This is the browser can still do other things) and processing is visible, he "synchronization" is not this "synchronization"--we say that the Java of the shared data Synchronization (synchronized) A synchronous object refers to the behavior (action), One is a synchronized object that refers to a substance (shared data). 4, Java synchronization Mechanism has 4 kinds of implementation: (Some references on-line resources) ①threadlocal②synchronized () ③wait () and notify () ④volatile purpose: All in order to solve the multiple threads in the same variable access violation thre Adlocal ThreadLocal guarantees that different threads have different instances, the same thread must have the same instance, that is, each thread that uses the variable provides a copy of the variable value, each of which can independently changeThe copy of the other thread. Advantage: Provides the difference between a thread-safe shared object and other synchronization mechanisms: The synchronization mechanism is to synchronize multiple threads for concurrent access to the same resource, for communication between multiple threads, and ThreadLocal is to isolate data shares from multiple threads, fundamentally without sharing resources among multiple threads. This certainly does not require multiple threads to synchronize. A volatile volatile member variable is forced to reread the value of the member variable from shared memory each time it is accessed by a thread.    Also, when a member variable changes, forcing the thread to write the change back to the shared memory.    Advantage: So at any moment, two different threads always see the same value for a member variable. Reason: The Java language specification states that for optimal speed, a thread is allowed to save a private copy of a shared member variable and is compared to the original value of a shared member variable only if the thread enters or leaves the synchronization code block. This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the changes to the shared member variables in a timely manner.     The volatile keyword is a hint to the VM: you cannot save its private copy for this member variable, but you should interact directly with the shared member variable. Usage tip: Use volatile on member variables accessed by two or more threads.        You do not have to use the variable you want to access when it is already in a synchronized code block, or is a constant. thread to improve efficiency, a member variable (such as a) copy a copy (such as b), the thread of access to a actually access is B. Synchronization of A and B occurs only for certain actions, so there is a and B inconsistency. Volatile is used to avoid this situation. Volatile tells the JVM that the variable it modifies does not retain the copy, directly accesses the main memory (the read operation is good for a long time; there is a need for communication between threads, which is not available in this article) Volatile variables have synchronized visibility characteristics, but do not have atomic properties. This means that threads can automatically discover the latest values of volatile variables. Volatile variables can be used to provide thread safety, but can only be applied to a very limited set of use cases: there is no constraint between multiple variables or between the current value of a variable and the modified value. You can use volatile variables instead of locks in a limited number of situations. For the volatile variable to provide ideal thread safety, the following two conditions must be met: The write to the variable does not depend on the current value, and the variable is not contained in the invariant with other variables. Sleep () vs wait () Sleep is the thread class (thread) method that causes this thread to pause execution for a specified time, giving the execution opportunity to another lineThe monitoring status remains, and will be restored automatically when the Calling sleep does not release the object lock. Wait is a method of the object class that calls the wait method on this object to cause this thread to discard the object lock, enter the waiting lock pool waiting for this object, and only after the Notify method (or Notifyall) is issued for this object the thread enters the object lock pool ready to get the object lock into the running state. (If the variable is declared volatile, it will be consistent with main memory on every access, if the variable is accessed in the synchronization method or synchronization block, when the lock is obtained at the entrance of the method or block, and the lock is released when the method or block exits) the variable is synchronized.  ) Iv. examples: Demo1:package test.thread; Class syntest{//non-synchronous static void method (thread thread) {System.out.println ("Begin" +thread.getname ()); try{thread.sleep (2000);} catch (Exception ex) {ex.printstacktrace ();} System.out.println ("End" +thread.getname ());} Synchronous mode One: Synchronous method synchronized static void Method1 (thread thread) {//This method is a synchronous method, and only one thread can come in System.out.println at a time ("Begin" + Thread.getname ()); Try{thread.sleep (2000);} catch (Exception ex) {ex.printstacktrace ();} System.out.println ("End" +thread.getname ());} Synchronous mode two: synchronous code block static void Method2 (thread thread) {synchronized (Syntest.class) {System.out.println ("Begin" + Thread.getname ()); Try{thread.sleep (2000);} catch (Exception ex) {ex.printstacktrace ();}  System.out.println ("End" +thread.getname ());}} Sync mode three: Use the Sync object lock private static object _lock1=new Object ();p rivate static byte _lock2[]={};//This lock is said to improve performance. Originating from: The smaller the lock object the better the static void Method3 (thread thread) {synchronized (_LOCK1) {System.out.println ("Begin" +thread.getname ()); Try{thread.sleep (2000);} catch (Exception ex) {ex.printstacktrace ();} System.out.println ("End" +thread.getname ());}} public static void Main (string[] args) {//start 3 threads, here with anonymous class for (int i=0;i<3;i++) {new Thread () {public void Run () {method ( This),//method1 (This),//METHOD2 (This),//method3 (This);}}.      Start ();}}} Demo2:package Test.thread;  Import Com.util.LogUtil; public class SynTest2 {public static void main (string[] args) {Callme target=new Callme (); Caller ob1=new Caller (target, "Hello"); Caller ob2=new Caller (target, "Synchronized"); Caller ob3=new Caller (Target, "World");}} Class callme{synchronized void Test () {LogUtil.log ("test is: Once a thread enters an instance of any synchronization method, another thread will not be able to enter another synchronization method for that same instance, However, the non-synchronous method of the instance can still be called ");} void Nonsyncall (String msg) {LogUtil.log ("[" +msg); LogUtil.log ("]");} synchronized void SyncAll (String msg) {logutil.logprint ("[" +msg); LogUtil.log ("]");}} Class Caller implements Runnable{string msg; Callme Target; Thread T; Caller (Callme target,string msg) {this.target=target;this.msg=msg;t=new Thread (this); T.start (), public void Run () {//  TODO auto-generated Method Stub//target.nonsyncall (msg); Target.syncall (msg); Target.test ();} }


This article turns from http://www.cnblogs.com/mengyuxin/p/5358364.html

Thread Implementation Async

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.