Java Concurrency Programming Combat (chapter_1) atomicity

Source: Internet
Author: User
Tags visibility

The bully looked at a lot of multi-threaded books, always thought that he was not qualified to read the book. There is a feeling of high-rise lobby, by a variety of networks, friends, colleagues a meal plus a meal of propaganda and praise, more or less in the heart of a sense of fear. February 28 After the good began to look, found that, in fact, there is absolutely no need. In addition to the translation of the rotten (a large section of Chinese down, sometimes you will dozens: This TM want to say is a Shen me gui), all, multithreading must grasp the knowledge points, in-depth point, all covered therein, can only say, a book in hand, million thread not worry about that! Of course, you have to read it all, and after that, you have the effect. I recommend, read the Chinese version of this book, do not and which paragraph of lengthy words in that excessive entanglement, try to read a paragraph, and then get the most important sentence in this paragraph, or you will fall into the Chinese reading comprehension of the vicious circle, and suspect that your high school Chinese teacher is not a sports teacher cameo!! I give an example: 13 page Eighth paragraph, I read the whole paragraph three times obstinately did not want to understand the front so many words, is what to use, is the last word is the core: tell you, thread security, the most formal definition should be what! (I am allowed to pay tribute to some of the translation of this book, the so-called "Professor", under your guidance, so that our will and endurance more on a step, life is more perfect! )

One, multi-threaded development to balance several points

Looked at a number of times the catalogue, plus looked at the first part, found that to do multi-threaded development, is nothing more than the balance of the following points

    • Security
    • Active Sex
      • Infinite loop problem
      • Deadlock problem
      • Hunger issues
      • Live lock problem (this has not been specifically learned)
    • Performance requirements
      • Problem with throughput
      • Scalability Issues
Second, multi-threaded development to focus on the development point

To want to ping very good above points, the book in a gradual manner will be multi-threaded development of the most should cultivate a few points, to explain:

    • Atomic Nature
      • First check and then execute
      • Atomic class
      • Locking mechanism
    • Visibility of
      • Re-arrange
      • Non-64-bit write problem
      • Publication of objects
      • Enclosing an object
    • Non-denaturing

In a book written by a native native, introducing the threading Tools API, I saw this sentence: The outside practice atom, the inside practice is visible. Feel this is especially important in multi-threading. I have praise, last year also remember the early morning of the online multi-store, the last project to start a class loading errors, a bunch of people over to see the problem, the base of the big God stood in the back of the elder brother, the last faint said: it is obvious that the problem of visibility, coupled with volatile, no, I ate the code!! Can be seen, multi-threaded these points, in the "Home Travel", life and work is how common and important! No problem does not matter, as long as one out, it will be a big headache problem, because you do not have to troubleshoot the root cause in this. So we need to practice good foundation, try to avoid the emergence of multi-threaded problems! Instead of just using frames and stacks of code!

Iii. Security issues under atomicity

1. What is wrong with the following code?

publicclassimplements Servlet{    privatelong0;    privatelonggetCount(){        return count;    }    publicvoidservice(ServletRequest req, ServletResponse resp){        extractFromRequest(req);        factor(i);        ++count;        encodeIntoResponse(resp,factor);    }}

Thinking: How to make an ordinary class thread safe? What is a class called a state, and what is called a stateless state?

2. Answer the above code

    • A requested method, the instance is one, so each request accesses the same object
    • For each request, a thread is used, which is the typical multithreaded model
    • Count is an object state property that is shared by multiple threads
    • ++countNot a single atomic operation (partitioning: Copy count-> to copy-to-clone, using copy-write-back count, three-step)
    • Multiple threads may modify the count value more than once, but the result is the same

3. Using atomic classes to solve the above code problem

public   Unsafeconuntingfactorizer implements  servlet{private  final     Atomiclong count = new  atomiclong (0 ); private  long  getcount  () {return  count. get     (); } public  void  service  (ServletRequest req,        Servletresponse resp) {BigInteger i = extractfromrequest  (req);        biginteger[] factors = factor  (i); Count. incrementandget  ();        //uses the atomic method of the new atomic class  encodeintoresponse     (Resp,factor); }}

4. The atomic class is not omnipotent either.

//In complex scenarios, use multiple atomic classes of objects Public classUnsafeconuntingfactorizerImplementsservlet{Private FinalAtomicreference<biginteger> Lastnumber =NewAtomicreference<biginteger> ();Private FinalAtomicreference<biginteger[]> lastfactors =NewAtomicreference<biginteger[]> (); Public void Service(ServletRequest req, Servletresponse resp) {BigInteger i =extractfromrequest(req);if(i.equals(Lastnumber.Get())){//To judge the process first, and not to synchronize, not safe!             Encodeintoresponse(Resp,lastfactors.Get()); }Else{biginteger[] factors =Factor(i); Lastnumer.Set(i); Lastfactors.Set(factors);Encodeintoresponse(resp, factors); }    }}

Thinking: What is called a compound operation?

5. Let's start by listing a common compound operation

publicclass LazyInitRace {    privatenull;    publicgetInstace(){        ifnull){            newExpensiveObject();        }        return instace;    }}

Watch out, this is a piece of code we detest! If this code is not analyzed, I'm sorry, go out to the left ~

6. Raising awareness of "first judgment and treatment"

    • If there are no synchronization measures, it is not safe to judge a state directly and then set the value.
    • The if operation and the code in the code below are fast, far from being atomic
    • If the If judgment is complete, then the thread hangs, the other threads enter the process of judgment, and the same state goes into the IF statement block.
    • Of course, there is only one thread to execute the program, please ignore (that is called to use the program?) )

7. The problem with the performance comes

//In complex scenarios, use multiple atomic classes of objects Public classUnsafeconuntingfactorizerImplementsservlet{Private FinalAtomicreference<biginteger> Lastnumber =NewAtomicreference<biginteger> ();Private FinalAtomicreference<biginteger[]> lastfactors =NewAtomicreference<biginteger[]> ();//This is finally in sync!      Public synchronized void Service(ServletRequest req, Servletresponse resp) {BigInteger i =extractfromrequest(req);if(i.equals(Lastnumber.Get())){//To judge the process first, and not to synchronize, not safe!             Encodeintoresponse(Resp,lastfactors.Get()); }Else{biginteger[] factors =Factor(i); Lastnumer.Set(i); Lastfactors.Set(factors);Encodeintoresponse(resp, factors); }    }}

Think: There is no kind of "Guan Gong swing broadsword, a cut a large" feeling?

8. Appeal Code Analysis

    • Plus the synchronized keyword does solve multi-threaded access, class security issues
    • But each time a thread is calculated, all requests become serial
    • Requests less than 100/s actually can accept, but then high, this is completely problematic code
    • Performance problems, and then the network inside, is the heart of the eternal scar ~

9. A solution for atomicity, performance issues

//In complex scenarios, use multiple atomic classes of objects Public classCachefactorizerImplementsservlet{PrivateBigInteger Lastnumber;PrivateBiginteger[] lastfactors;Private LongHitsPrivate LongCachehits; Public synchronized Long gethits(){returnHits } Public synchronized Double Getcachehitradio(){return(Double) Cachehits/(Double) hits; } Public void Service(ServletRequest req, Servletresponse resp) {BigInteger i =extractfromrequest(req); biginteger[] factors =NULL;synchronized( This) {++hits;if(i.equals(Lastnumber))                {++cachehits; factors = lastfactors.Clone(); }        }if(Factors = =NULL) {factors =Factor(i);synchronized( This) {Lastnumer = i; Lastfactors = factors.Clone(); }        }Encodeintoresponse(resp, factors); }}

In the modification of the status value, only to lock, usually the state value of the read operation can not be locked, of course, the most time-consuming calculation process, but also to synchronize, in this case, will further improve performance.

Java Concurrency Programming Combat (chapter_1) atomicity

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.