The third of concurrent programming

Source: Internet
Author: User
Tags finally block

Introduction

For a long time not to talk with you about the concurrency, today LZ busy to have nothing to talk with you about concurrency. Because of the time past a bit long, so the LZ is not in accordance with the common sense of the card, but the understanding of their own record in this, if you are the ape friends feel some harvest, on the point of a recommendation or message inspired LZ, if you feel wasted their precious time, can also send complaints.

Well, the nonsense is not much to say, start our concurrent journey now.

Simple classification of concurrent programming

  

Concurrent common programming scenarios, in a nutshell, need to coordinate collaboration between multiple threads, ensuring that the program executes at its own will. So how exactly should you coordinate multiple threads?

This problem is relatively broad, in general, we follow the way of latitude to simply distinguish, there are the following two ways:

  1, the first is to take advantage of the internal mechanism of the JVM.

  2, the second is the use of mechanisms outside the JVM, such as the JDK or some class libraries.

The first method is generally implemented by means of the synchronized keyword, and the second is usually done manually using the classes in the JDK. The two approaches are very similar, and their differences are somewhat similar to the difference between C + + and Java garbage collection, which is more flexible and efficient, and the way that Java automated garbage collection is more secure and convenient.

Concurrency has always been considered to be the advanced features of programming, but also a lot of big companies in the interview is more concerned about the part, so master the simple skills of concurrency, or can let their technology precipitate a qualitative leap.

  

The internal mechanism of the JVM--synchronization Chapter

The JVM has a lot of internal synchronization mechanisms, which in some cases are very worthwhile for us to use and learn, so let's take a look at what internal synchronization the JVM provides.

  Forced synchronization mechanism of 1,static

Static this keyword believe that everyone is not strange, but it comes with the synchronization mechanism is estimated that many apes do not know. For example, the following simple class.

View Code

First of all, this piece of code will become the following after compiling, you can use the Anti-compilation tool to verify.

View Code

But when the JVM actually executes this code, it turns out to look the same.

View Code

That is, when you actually execute a static initialization code block for a class, the virtual machine internally synchronizes it, which ensures that no matter how many threads load a class at the same time, the code in the static block executes and executes only once. This is an effective application in the singleton model, and the ape friends are interested to look at the LZ before the single-mode blog post.

  Synchronization mechanism of 2,synchronized

Synchronized is a synchronization mechanism provided by the JVM that can modify methods or blocks of code. In addition, when modifying a block of code, synchronized can specify objects that are locked, such as this, the class literal constant, and so on. When using synchronized, we typically lock on specific attributes and sometimes create a lock object specifically.

Add the Synchronized keyword directly to the method, or use this, class literal constants as a lock method is more commonly used, but also relatively simple, here is no longer an example. Let's take a look at the way a property is locked, as follows.

View Code

This is generally preferable to locking using this or class literal constants, because the synchronized decorated non-static member method is locked by default with this, whereas the static member method of the synchronized adornment defaults to the lock used by the class literal constant, Therefore, if you use this or the literal constants directly in the synchronized code block, you may inadvertently create a mutex with the Synchronized method. In general, the use of attributes to lock, can more effectively improve the concurrency, so as to ensure that the program is correct, as far as possible to improve performance.

Then look at a more special code, if the ape friends often look at the JDK source code or some good open source framework source code, may have met this way.

View Code

Lock is a dedicated object for monitoring, and it has no practical meaning, just to work with synchronized to complete a unified lock on two properties. Of course, in general, you can also use this instead of lock, there is actually no death of the provisions, can be determined according to the actual situation. There is a more non-recommended way, that is the following.

View Code

This kind of locking method is more challenging than the degree of attention, in case any careless order is mistaken, it may cause a deadlock. So if you have to use this method, be prepared to be executed by your boss.

  

A detailed explanation of the JVM external mechanism-synchronization Chapter

  

The synchronization mechanism that corresponds to the internal JVM is the external synchronization mechanism, which can also be called a programmatic synchronization mechanism. Next, let's look at some common external synchronization methods.

  Reentrantlock (re-entry Lock)

Reentrantlock is a class in the locks of the JDK and is designed to compensate for some of the shortcomings of the Synchronized keyword. Let's take a look at what the Synchronized keyword is all about, and then we'll try to use Reentrantlock to solve the problem.

  1) Synchronized keyword synchronization, waiting for the thread will not control, can only death.

Workaround: Reentrantlock can use the Trylock (timeout, unit) method to control when the lock is waiting to be acquired, or it can be returned immediately using the parameterless Trylock method, which avoids the possibility of deadlock.

  2) Synchronized keyword synchronization, there is no guarantee of fairness, it will be wired to queue the phenomenon.

Workaround: Reentrantlock can use the constructor method Reentrantlock (fair) to enforce the use of fair mode, which ensures that the order in which the threads acquire the locks is in the order of waiting, while the synchronized is synchronized. is the default non-fair mode, but the JVM can be a good guarantee that threads are not starved.

Reentrantlock has such advantages, of course, there are deficiencies. The main disadvantage is that Reentrantlock requires the developer to manually release the lock and must be released in the finally block.

Here are two simple examples of reentrantlock, please watch the ape friends.

View Code

The above shows the basic usage of reentrantlock and the wait for a limited time, so let's look at how Reentrantlock is used when multiple objects need to be locked. As you can see from the following code, the usage is very similar to the one in synchronized above.

View Code

The internal mechanism of JVM--condition waiting

  

Now that we have discussed the mechanism of internal synchronization within the JVM, let's take a look at the conditional wait mechanism inside the JVM. The class in Java has a common parent class object, and in object there is a wait local method, which is a magical method.

It can be used to coordinate the collaboration between threads, the use of the way is relatively simple, take a look at the following example, you are basically getting started oh.

View Code

This is one of the most basic examples where we use one thread to wait for another thread's notification on an object object, and when another thread notifies, the waiting thread will continue to run. In fact, the first contact with this thing, is not feeling very interesting.

The most common scenario in a wait scenario is when you construct a very expensive object, such as when the JDK dynamic agent uses this method to generate the proxy class. JDK6 before generating a proxy class, it detects whether a identity is in the build, and if it is being generated, JDK6 waits on the object until the proxy class being generated is finished and is fetched directly from the cache.

One thing that needs to be reminded here is that the wait,notify and Notifyall methods must obtain a lock on the current object before using it, or they will tell you about an illegal monitoring state exception. Another point is that if there are multiple threads waiting in wait, the call to notify will randomly notify one of the threads and not be notified in order. In other words, notify's notification mechanism is unfair, and notify does not guarantee that the thread that calls the wait method first is awakened. The Notifyall method does not have this problem, it notifies all waiting threads in wait.

  

A detailed explanation of JVM external mechanism--condition waiting chapter

  

Above we have seen the JVM's own conditional control mechanism, which is implemented using the local method wait. Then there is a class condition in the JDK's class library to compensate for the lack of the wait method itself. As before, let's talk about the shortcomings of wait.

  1) Wait method when using a method with a parameter, wait (timeout) or wait (Timeout,nanos), can not feedback whether it is awakened or arrive at the wait time, most of the time, we will use the loop (as in the example above) to detect whether the condition is reached.

WORKAROUND: Condition can use the return value to identify whether the time-out is reached.

  2) because the Wait,notify,notifyall method needs to acquire the lock of the current object, when there are multiple conditional waits, you need to get the lock of multiple objects sequentially, which is a very nasty and cumbersome thing.

Solution: Condition need to get lock locks, a lock can have multiple conditions.

The first question is better understood, but condition's await method has more than one return parameter Boolean to identify whether it is awakened or timed out. But the second problem is a bit more cumbersome, so here's a simple example, as follows.

View Code

This is an example of a multi-condition. The basic logic is that thread 1 waits for thread 2 notification first, and then thread 2 waits for thread 1 notification. Keep in mind that this is a two different condition. As you can see, if you use wait, you must obtain two locks two times, and there may be a deadlock. Next, let's see how condition implements the same functionality.

View Code

As you can see, we just need to get the lock once, and internally we can use two or more conditions instead of having to get locks multiple times. This method is more intuitive and greatly increases the readability of the program.

  

Detailed JVM external mechanism--thread collaboration

  

In addition to the above Reentrantlock and condition, there are many tools that help ape friends coordinate threads. Next we'll have a one by one-face ripe.

  1,countdownlatch

This class is designed to help apes make it easy to implement a scenario in which a thread waits for several other threads to finish something before it can continue. For example, the following program.

View Code

The main thread of the program waits for Countdownlatch to make 10 calls to the Countdown method before it continues execution. We can see from the printed results, although sometimes the completion of the task of printing will appear in the main thread after the completion of execution, but this is only because the countdown has been executed, the main thread of the print statement first step execution.

  2,cyclicbarrier

This class is designed to help apes make it easy to implement multiple threads to start a scene, like a race, as long as everyone is ready, then start rushing together. For example, the following program, all the threads are ready to start executing together.

View Code

  3,semaphore

This class is designed to help ape friends to achieve a convenient control of the number of scenes, can be the number of threads or the number of tasks and so on. Let's take a look at this simple piece of code.

View Code

As can be seen from the results, LZ set a total of 10, but opened 100 threads, but eventually only 10 threads get the semaphore, if the 10 threads do not actively call the release method, then the remaining 90 threads will hang dead together.

  4,exchanger

This class is designed to help ape friends to easily implement the two-thread exchange of data scenes, easy to use, look at the following code.

View Code

Two threads the caller is suspended when only one thread calls the Exchange method, and the data is exchanged when both are completed. The thread is in a pending state until either party has called exchange.

  

Summary

  

Today LZ and you have a look at some of the basics of Java concurrent programming, it is necessary to master the above information for concurrent programming. I hope you can get some of the ape friends, we see you next time!

Original link: http://www.cnblogs.com/zuoxiaolong/p/con2.html

The third of concurrent programming

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.