(RPM) Java Multithreading Synchronous and asynchronous

Source: Internet
Author: User
Tags java reference

Java thread synchronization and asynchronous thread pool
1) Multi-threaded concurrency, multiple threads simultaneously request the same resource, will inevitably cause the data of this resource unsafe, a thread modified B line

Process, and the B thread modifies the math of a thread processing. This is obviously due to global resources, sometimes to solve

In this case, priority is given to using local variables, and fallback to using synchronous blocks of code, for which security considerations must be sacrificed

System processing performance, plus in multi-threaded concurrency when the most intense resources, which enables the synchronization mechanism of threads

Synchronization: A thread wants to request a resource, but this resource is being used by the B thread because the synchronization mechanism exists, a thread requests

No, what to do, a thread can only wait to continue

Async: A thread wants to request a resource, but this resource is being used by the B thread because there is no synchronization mechanism present, a thread

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, such a thread to die will lead to the entire

The process crashes, but there is no synchronization mechanism, performance is improved

Implementing Multithreading in Java

1) inherit thread, rewrite the Run method inside

2) Implement Runnable interface

Doug Lea preferred the latter, first, Java does not have a single inheritance limit second, you can also isolate code

Thread pool

It is necessary to know that any resource creation, including threads, in a computer consumes system resources. In Web services, for Web service

The server must respond as quickly as possible, and it is not allowed to create a thread service every time the user submits the request button

。 To reduce the user's wait time, threads must be pre-created, placed in the thread pool, and hashtable this number

According to the structure to realize, looked at the Apach HTTP server thread pool source code, with IS is hashtable,key with thread object,

Value with Controlrunnable,controlrunnable is the only thread in the thread pool that can work, and it is assigned to the thread pool.

Threads to provide services externally.

For security reasons, the thread pool of the Apach HTTP server is synchronized. I heard that WebLogic has asynchronous implementation, no research

I'm not sure.

---------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------
First, the key words:

Thread (threads), Thread-safe (thread-safe), intercurrent (concurrent)

Synchronized (synchronous), asynchronized (asynchronous),

volatile (variable), Atomic (atomic), Share (shared)

Second, summarize the background:

A read-write shared file writing, Ho, the boy, unexpectedly pulled out these fragmentary and is the knowledge point. So Google and

Read the "Java Reference", "effective Java Second Edition", to summarize the future work of the study

Test.

Third, the concept:

1. When do I have to synchronize? What does synchronization mean? How do I sync?

To maintain the correct visibility across threads, as long as you share non-final variables between several threads, you must use the

Synchronized (or volatile) to ensure that one thread can see changes made by another thread.

Synchronization is necessary for reliable communication between threads and for mutually exclusive access. This is due to the Java language Specification of memory

Model, which specifies when and how changes made by a 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. Example: if 2 lines

The process wants to communicate and share a complex data structure, such as a linked list, you need to ensure that they do not conflict

The B-thread writes the data to the linked list during a thread reading (a gets the lock, B must wait for a to release the lock).

In order to achieve this, Java has implemented a smart system based on an old process synchronization model, monitor,

Wonderful scenario: The monitor is a control mechanism that can be thought of as a small box that can only hold one thread, once a

The thread enters the monitor, and the other threads must wait until the thread exits monitoring. In this way, a monitor

A shared resource can be guaranteed to be used by only one thread at a time. This approach is called synchronization. (Once a thread enters a

The other thread will not be able to enter another synchronization method for that same instance, but the non-synchronous side of the instance

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 feature to implement a coordinated access protocol to shared data

, so that only one thread can use the shared data at a time.

Visibility is more complex, and it must ensure that changes to the shared data are made before the lock is released for another

Threads are visible-if there is no guarantee of this visibility provided by the synchronization mechanism, the shared variables that the thread sees may be pre-modified

Values or inconsistent values, which will cause many serious problems

Summary: To prevent multiple threads from concurrently modifying the same data, synchronization is required, otherwise the data will be inconsistent (that is, the

: Thread-safe. As in the Java Collection framework, hashtable and vectors are thread-safe. Most of our programs are not lines.

Because there is no synchronization, and we do not need to, because most of the situation does not have a multi-threading environment at all.

2, what is called Atomic (atomic operation)?

A Java atomic operation is an operation that is not interrupted. (Is mutual exclusion and visibility?!) )

Is it true that atomic manipulation can actually achieve the thread-safe synchronization effect? There are actually some atomic operations that are not necessarily thread safe

Of

So, under what circumstances are atomic operations not thread-safe? This may be the cause: Java threads allow threads to

Save a copy of the variable in its own memory area. Allows a thread to work with a local private copy rather than using the main memory value every time

To improve performance (I humble opinion: Although the atomic operation is thread-safe, each thread can get the variable (read operation), the

Self-toying with its own copy, the update operation (write operation) because it is not written in the primary, 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, in addition to double and long

The other primitive types of the type are usually represented using 32-bit, whereas double and long are usually represented by a 64-bit. In addition, the object is cited

The use of native pointers is usually 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. So

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. In

Again, it is emphasized that all platforms are guaranteed to be of the range of tables, and the operation of 32-bit and smaller values is atomic.

3. Don't confuse: synchronous, asynchronous

For example: Ordinary B/s mode (synchronous) Ajax Technology (asynchronous)

Synchronize: Submit request, wait for server processing, and then return to this period the client browser cannot do anything

Asynchronous: Requests are processed through event triggering server processing (which is still something the browser can do)

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

A synchronized object is a behavior (action), and a synchronized object refers to a substance (shared data).

4, Java synchronization Mechanism has 4 ways to achieve: (partial reference to online resources)

①threadlocal②synchronized () ③wait () and notify () ④volatile

Purpose: To solve the access violation of the same variable in multi-threading
ThreadLocal
ThreadLocal ensure that different threads have different instances, the same thread must have the same instance, that is, for each use of the

A variable's thread provides a copy of the value of the variable, and each thread can change its own copy independently, rather than with other threads

The replica conflict.

Advantage: Provides thread-safe shared objects

Differences from other synchronization mechanisms: Synchronization is to synchronize multiple threads for concurrent access to the same resource, for multiple thread

While ThreadLocal is a data share that isolates multiple threads, it is fundamentally not sharing resources among multiple threads

, which of course does not require multiple threads to synchronize.

Volatile
A volatile-modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by the 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 in order to get the best speed, a thread is allowed to save a private copy of a shared member variable, while

It is compared to the original value of the shared member variable only if the thread enters or leaves the synchronization code block. This way, when multiple threads are simultaneously associated with a

When interacting with an object, it is important to note that the thread gets the changes to the shared member variables in a timely manner. And the volatile keyword is

is to prompt 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. When the variable to be accessed is already in the

Synchronized code blocks, or constants, you do not have to use them.
thread to improve efficiency, a member variable (such as a) copy a copy (such as b), the thread of access to a actually access the

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 its modified variables do not retain copies and are accessed directly in main memory (read operations are used for a long time

Communication between threads is required, not in this article)

Volatile variables have synchronized visibility characteristics, but they do not have atomic properties. This means that threads can self-

Find the latest value of the volatile variable. Volatile variables can be used to provide thread safety, but can only be applied to very limited

A 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. To make a volatile variable

Thread safety, you must meet the following two conditions:

A write to a variable does not depend on the current value, and the variable is not contained in an invariant that has other variables.

Sleep () vs wait ()
Sleep is a thread-class method that causes this thread to pause execution for a specified time, giving the execution opportunity to another thread, but the supervisor

The control state remains, and will be restored automatically. 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 and enter the waiting lock waiting for this object

The Notify method (or Notifyall) is issued for this object only after this thread has entered the object lock pool ready to get the object lock

into a running state.

(If the variable is declared volatile, it will be consistent with main memory on each visit; If the variable is in a synchronous method or synchronous block

is accessed when a lock is obtained at the entrance of the method or block and the lock is released when the block exits and 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: Synchronization method

synchronized static void Method1 (thread thread) {//This method is a synchronous method, with only one

A thread can come in

SYSTEM.OUT.PRINTLN ("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 ());

}

}

Synchronization mode three: Using a Synchronous object lock

Private static Object _lock1=new object ();

private static byte _lock2[]={};//This lock is said to improve performance. From: The smaller the lock object, the better

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 and use anonymous classes here

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, the other thread will not

Other synchronization methods that enter the same instance, but the asynchronous 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 ();

}

}

(RPM) Java Multithreading Synchronous and asynchronous

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.