Learning notes: The first knowledge of Java concurrent Programming learning concurrent

Source: Internet
Author: User
Tags semaphore

First, the initial knowledge concurrent

The first time I saw the use of concurrent was written in a colleague's extraction system code, when this part of the code is not completed, there are many problems, another colleague took over the development of this part of the code, because he does not have the experience of multi-threading development, so I will help the analysis together. The first to see this is very annoying ah, because of their exposure to Java time is very short, even synchronized do not know how to use it, suddenly found that there is such a complex thing. Then you have to start learning, after all, it is used, the first goal is to understand how the various classes and methods of this thing to use, and then look at the colleague's code is probably clear. It feels like most people can use it.

Here is a section of the application

 Public classVoiceextractrunnableImplementsRunnable {@Override Public voidrun () {//Create a thread poolExecutorservice Service =Executors.newcachedthreadpool (); //declares a collection that holds the results of each task (thread) executionList<future<voiceextractexpertinrulevo>> futures =NewArraylist<future<voiceextractexpertinrulevo>>(Rules.size ()); //Loop Submit Task         for(Voiceextractexpertinrulevo rulevo:rules) {rulevo.setextractparamvo (VO); Futures.add (Service.submit (Newvoicerulecallable (Rulevo)); }         for(future<voiceextractexpertinrulevo>f:futures) {            Try{Voiceextractexpertinrulevo R=F.get (); Returnrules.add (R); //gets the returned result after the task execution is completed}Catch(Exception e) {logger.error ("", E); }        }        //when all tasks are completed, close the thread poolService.shutdown (); }}

After reading this code (omitting most of the business logic code), you can feel the advantage that thread execution and result acquisition can be asynchronous, which is really helpful for development. The code structure is also relatively clear.

But at this point I am mostly in the stage of being able to use it, and I am not concerned about how much code is important in concurrent. Recently in the basic knowledge of Java learning, see thread safety when concurrent began to enter my vision, then I know it is so rich, so only to start a little understanding. The process has also been felt that the engineers who write these code are really powerful, in the process of practice to summarize such a good code, for the vast number of developers to use.

Second, the main class
Executor: The performer of the specific runnable task. Executorservice: A thread pool manager, with a variety of implementation classes, I'll cover some of them. We can submit the runnable,callable to the pool for dispatch. Semaphore: A count semaphore Reentrantlock: a reentrant Mutex lock lock, similar in function to synchronized, but much more powerful. Future: An interface that interacts with the runnable,callable, such as the result of a thread executing after the end of execution, and so on, and also provides a cancel termination thread. Blockingqueue: Blocking queue. Completionservice:executorservice extension, you can get the countdownlatch of the thread execution result: A synchronization helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed. Cyclicbarrier: A synchronization helper class that allows a set of threads to wait for each other until a common barrier point is reached future:future represents the result of an asynchronous calculation. Scheduledexecutorservice: A executorservice that can be scheduled to run after a given delay or to execute commands on a regular basis.

Above are some common classes, refer to this article, written more clearly: http://www.cnblogs.com/aurawing/articles/1887056.html

After I personally read the code, I was impressed with the following classes:

Concurrenthashmap: Support for concurrent Hashmapabstractqueuedsynchronizer: Provides a basic feature implementation of the sync lock, including exclusive and shared locks

For Concurrenthashmap This class is a hashmap that adapts to concurrent scenarios and is built on a separate lock basis. Its internal structure can be divided into n segments, each with its own concurrency lock, so that writing can be written to different segments, which improves concurrency performance.

Reference : http://blog.csdn.net/fw0124/article/details/43308193

Abstractqueuedsynchronizer is a key abstraction for locks in the concurrent package, mainly providing a state field for controlling concurrency, which ensures a multi-threaded locking mechanism by controlling the atomic states of the status. This class is an abstract class, and many of the scenario implementations need to be implemented in a particular subclass.

Reference:

Http://www.infoq.com/cn/articles/jdk1.8-abstractqueuedsynchronizer

Http://www.infoq.com/cn/articles/java8-abstractqueuedsynchronizer

Third, some of the knowledge points to learn

These days in the source code is also constantly looking for various materials on the Internet, or learned a lot of things.

The split Lock (lock spliting) is that if the original program has multiple logic in the same lock, but the logic is independent of each other, it can be disassembled (spliting) for the use of multiple locks, each lock guarding different logic.

A split lock can sometimes be extended into a collection of large, small, locked blocks, and they belong to separate objects, which is the case of a separate lock (lock striping). (excerpt from the Java Concurrency Programming practice)

There is a better explanation for the split Lock: The split lock can sometimes be expanded into a set of lock blocks, and they belong to separate objects, which is the case of a separate lock. For example, the implementation of CONCURRENTHASHMAP uses an array of 16 locks, each of which guards 1/16 of HashMap. Assuming that the hash value is evenly distributed, this will reduce the lock request to about 1/16 of the original. This technology allows the CONCURRENTHASHMAP to support 16 concurrent writers. The number of locks can also increase when heavy-duty access to multiprocessor systems requires better concurrency. --Excerpt from Developerworks

Sun.misc.Unsafe is a class that encapsulates a lot of bottom-level operations, but there is not much information on the web, but in the concurrent package, the most important thing is that the method Compareandswap is atomic and can be used without locking itself. Look at the lock in the concurrent package is mainly through this method to achieve the lock state management.

But the internet also mentioned that he can operate memory, it is no wonder called unsafe this, if in Java code casually use, that Java will become and C + + almost, hehe. So in addition to the unit in the JDK, you cannot use this class directly in the code you write.

volatile keyword: this keyword is required to have visibility when accessing volatile modified shared data in a multithreaded environment.

I really do not know how to explain it, recommended two good articles:

Http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

Http://www.cnblogs.com/dolphin0520/p/3920373.html

Four, small feeling

While looking at the code in the concurrent package, it is true that some fine seconds of design, such as the lock design, a combination of abstraction and implementation of good design. Many of the small details inside reflect the technical skills, and think of why they do not design this code.

I feel two things:

1, no practical problems to solve

For example, the code in this concurrent for concurrent programming, to tell the truth in the work encountered not much, the general situation with synchronized can also be solved, used in. NET also used lock keyword. Delphi is also easy to use. So there is no good job scenario for you to solve these problems, to tell the truth you can not imagine.

2, the foundation is not solid

Actually read a lot of code are some basic applications, you say flow, files, concurrency These things are all the problems in the computer, as long as the mastery of these knowledge, in fact, in the actual encounter problems can be used. Otherwise, as a problem with some other methods to avoid, but lost the opportunity to write better code, long time has become mediocre

After a lot of work to learn the foundation, this period of time I feel that I can have more in the program, perhaps I can write code to 50 years old, at least I think 50 years old can still keep up with the times, write excellent code.

Learning notes: The first knowledge of Java concurrent Programming learning concurrent

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.