Java concurrent programming: synchronized, asynchronous ynchronized

Source: Internet
Author: User

Java concurrent programming: synchronized, asynchronous ynchronized

Although multi-threaded programming greatly improves the efficiency, it also brings some hidden dangers. For example, if two threads insert non-duplicate data to a database table at the same time, the same data may be inserted in the database. Today, we will discuss thread security issues and the mechanisms provided in Java to solve thread security issues.

The following is the directory outline of this article:

1. When will thread security problems occur?

2. How to Solve the thread security problem?

3. synchronized synchronization method or synchronization Block

If there are any mistakes, please forgive me and welcome criticism and correction.

1. When will thread security problems occur?

Thread security issues do not occur in a single thread, but in multi-threaded programming, it is possible to access the same resource at the same time. Such resources can be of various types: A variable, an object, a file, a database table, and so on. When multiple threads access the same resource at the same time, there will be a problem:

Because the execution process of each thread is uncontrollable, the final result may be in conflict with the actual desire or directly cause program errors.

A simple example:

Now there are two threads that read data from the network and then insert data into a database table. Duplicate data cannot be inserted.

Therefore, there must be two operations during data insertion:

1) check whether the data exists in the database;

2) If yes, It is not inserted. If no, It is inserted into the database.

If the two threads are represented by thread-1 and thread-2 respectively, both thread-1 and thread-2 read data X at a certain time point, this may happen:

Thread-1 checks whether data X exists in the database, and then thread-2 checks whether data X exists in the database.

RESULT Both threads check that data X does not exist in the database, so both threads insert data X into the database table respectively.

This is a thread security issue, that is, when multiple threads access a resource at the same time, the program running result is not expected.

This resource is called a critical resource (also known as shared resources ).

That is to say, when multiple threads simultaneously access critical resources (an object, an object attribute, a file, a database, etc.), thread security issues may occur.

However, when multiple threads execute a method, the local variables inside the method are not critical resources, because the method is executed on the stack, while the Java stack is private to the thread, therefore, thread security issues will not occur.

2. How to Solve the thread security problem?

In general, how does one solve the thread security problem?

Basically, all concurrency modes adopt the "serialize access to critical resources" solution to solve thread security issues. That is, at the same time, only one thread can access critical resources, it is also called synchronous mutex access.

Generally, a lock is added before the code to access the critical resource. After the critical resource is accessed, the lock is released so that other threads can continue to access the resource.

Java provides two methods for Synchronous mutex access: synchronized and Lock.

This article describes how to use synchronized and how to use Lock in the next blog.

3. synchronized synchronization method or synchronization Block

Before learning how to use the synchronized keyword, let's take a look at the concept: mutex lock, as its name implies: a lock that can achieve mutex access.

For example, if a thread adds a mutex lock to a critical resource, other threads can only wait when it accesses the critical resource.

In Java, each object has a lock mark (monitor), also known as a monitor. When multiple threads access an object at the same time, the thread can only access the Lock of this object.

In Java, you can use the synchronized keyword to mark a method or code block. When a thread calls the synchronized Method of the object or accesses the synchronized code block, this thread acquires the Lock of this object. Other threads cannot access this method for the moment. This thread will release the Lock of this object only after the method is executed or the code block is executed, other threads can execute this method or code block.

Below are a few simple examples to illustrate the use of the synchronized keyword:

1. synchronized Method

In the following code, two threads call the insertData object to insert data respectively:

1. public class Test {2. 3. public static void main (String [] args) {4. final InsertData insertData = new InsertData (); 5. 6. new Thread () {7. public void run () {8. insertData. insert (Thread. currentThread (); 9 .}; 10 .}. start (); 11. 12. 13. new Thread () {14. public void run () {15. insertData. insert (Thread. currentThread (); 16 .}; 17 .}. start (); 18 .} 19 .} 20. 21. class InsertData {22. private ArrayList <Integer> arrayList = new ArrayList <Integer> (); 23. 24. public void insert (Thread thread) {25. for (int I = 0; I <5; I ++) {26. system. out. println (thread. getName () + "inserting data" + I); 27. arrayList. add (I); 28 .} 29 .} 30 .}

 Obtain 【] 

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.