Talk about Java those things (i)--concurrent

Source: Internet
Author: User

In the world of programming, the most talked about is the most specific technical content is concurrent programming. Some students talk about concurrency, think of multiple threads, multiple processes. There are other concurrent programming programs, the answer is yes. There is a book called "Seven Concurrency Models in seven", which said 7 kinds of concurrent programming model, today's study, led us to enjoy 7 kinds of concurrent programming technology and the author of some thinking.

Before we begin to say concurrency, let's distinguish between concurrency and parallel. Concurrency is concurrency, parallel is parallelism. These two concepts, the author before writing this blog, is not clear their differences. Then I took a serious look at their definition to really understand.

Concurrency is about dealing with lots of things at once.

Parallelism is about doing lots of things at once.


Non-Chinese native people the difference between dealing with and doing is not profound, including the author in, but also how. But generally speaking, deal with has to deal with, the meaning of coping. Take a look at the example below.

My wife is a teacher. Like most of teachers, she is a master of Multitasks. At any one instant, she's doing one thing, but she has to deal with many things concurrently. While listening A is a child read, she might is off to calm down a rowdy classroom or answer a question. This is concurrenct and but it ' s not parallel. (That's only one of her.)

If she has a assistant, (one of them listening child ' s reading, the other answering the question), we now have something That ' s both concurrency and parallel.


The following author gives a parallel, serial, concurrent understanding. Think about the following scenario, Cook, Cook, a cook and two things.

Serial: The cook cooks first, waits for the rice to cook, then cooks. (I don't think there's a cook like that.) )

Concurrent: The cook put the rice in the rice cooker first, then began to cook, the last meal at the same time good. (The method of co-ordination)

Parallel: There are two cooks, one for cooking, the other for cooking. The final meal is done at the same time.


In general, to improve the overall performance of the system, parallelism and concurrency should be combined. You can think of distributed system as parallel systems. One node of distributed system wants concurrent node.


I. Threads and Locks

It can be seen from the title that this kind of concurrent programming is the most familiar way to achieve concurrency through multithreading and locking. When it comes to multithreading, it starts with a single thread. A single thread is actually a serial processing, English is called sequential programming. As you can see from this name, it is a sequential (queue)-based approach. In the multi-core era, this approach clearly does not give full play to hardware performance.

So the introduction of Multi-thread, multithreading. Multiple threads, handling tasks at the same time, much better, the performance should multiply it. But not necessarily. You imagine, you handle 10 things alone, and then slow down, but there is no communication with other people cost, 10 things 10 people do, see efficiency increased, but inevitably with people, who do what things, we have to discuss, this consultation, then there will be competition, some people think this thing is good, he wants to do, The other person wants to do the same thing at the same time, which introduces the problem of competition.

The list of issues to be handled by multithreading is as follows:

1. How to allocate the number of multithreading.

2. Multithreading how to ensure synchronization.

The first question seems simple, but it is not a good answer. But there is a basic formula: the best number of threads = ((thread wait time + Thread CPU time)/thread CPU time) * CPU kernel count

The mathematical formula is sorted out as follows:

Optimal number of threads = (thread wait time/thread CPU time + 1) * CPU kernel count


For example, the average CPU run time per thread is 0.5s, while the thread latency (such as IO) is 8 of the 1.5S,CPU core, and is estimated according to the formula above: ((0.5+1.5)/0.5) *8=32.

As can be seen from the formula above, the longer the thread waits (IO operation-intensive, network IO, disk IO, etc.), the more threads there are. The longer the thread CPU time (computationally intensive, such as encryption and decryption, video compression, file compression, etc.), the smaller the number of threads to be.  If the thread CPU time is infinite, the optimal number of threads = CPU kernel count. The network often said that there are several CPU core, with a few threads, or there is a certain truth, but is suitable for the calculation-intensive scenarios.

Import Java.math.BigDecimal;
Import Java.math.RoundingMode;
Import Java.util.Timer;
Import Java.util.TimerTask;

Import Java.util.concurrent.BlockingQueue; /** * A class that calculates the optimal thread pool boundaries. It takes the desired target utilization and the desired * Work queue memory consumption as input and retuns thread count
 and work queue capacity. * * @author Niklas SCHLIMM */Public abstract class Poolsizecalculator {/** * The sample queue size to Calcul
     Ate the size of a single {@link Runnable} element.

    * Private final int sample_queue_size = 1000; /** * accuracy of test run. It must finish within 20ms of the testtime otherwise we retry the test.
     This could is * configurable.

    * Private final int epsylon = 20;
     /** * control variable to the CPU time investigation.

    * Private volatile Boolean expired;
     /** * Time (Millis) of the "Test run in" CPU time calculation. * Private Final Long testtime = 3000;
     /** * Calculates the boundaries of a thread pool for a given {@link Runnable}.  * * @param targetutilization The desired utilization of the CPUs (0 <= targetutilization <= 1) * @param Targetqueuesizebytes the desired maximum work queue size of the thread pool (bytes) * * protected void Calculateb Oundaries (BigDecimal targetutilization, BigDecimal targetqueuesizebytes) {calculateoptimalcapacity (targetqueuesiz
        Ebytes);
        Runnable task = Creattask ();
        Start (Task); Start (Task);
        Warm up phase long CPUTime = Getcurrentthreadcputime (); Start (Task);
        Test Intervall CPUTime = Getcurrentthreadcputime ()-CPUTime;
        Long waittime = (Testtime * 1000000)-cputime;
    Calculateoptimalthreadcount (CPUTime, waittime, targetutilization); 
        } private void Calculateoptimalcapacity (BigDecimal targetqueuesizebytes) {Long mem = Calculatememoryusage (); BiGdecimal queuecapacity = targetqueuesizebytes.divide (new BigDecimal (MEM), roundingmode.half_up);
        System.out.println ("Target Queue Memory Usage (bytes):" + targetqueuesizebytes); System.out.println ("CreateTask () produced" + Creattask (). GetClass (). GetName () + "which took" + Mem + "
        Bytes in a queue ");
        System.out.println ("Formula:" + targetqueuesizebytes + "/" + mem);
    SYSTEM.OUT.PRINTLN ("* Recommended queue Capacity (bytes):" + queuecapacity);
     }/** * Brian Goetz ' optimal thread count formula, "Java Concurrency in Practice" (Chapter 8.2) * * @param CPU CPU time consumed by considered task * @param wait for time of considered TA SK * @param targetutilization Target utilization of the system */private void Calculateoptimalthreadcount (l
        Ong CPU, long wait, BigDecimal targetutilization) {BigDecimal waittime = new BigDecimal (wait); BigDecimal ComputETime = new BigDecimal (CPU);
        BigDecimal numberofcpu = new BigDecimal (Runtime.getruntime (). Availableprocessors ()); BigDecimal Optimalthreadcount = numberofcpu.multiply (targetutilization). Multiply (new BigDecimal (1). Add (WA
        Ittime.divide (Computetime, roundingmode.half_up));
        System.out.println ("Number of CPUs:" + numberofcpu);
        SYSTEM.OUT.PRINTLN ("Target utilization:" + targetutilization);
        System.out.println ("Elapsed Time (Nanos):" + (Testtime * 1000000));
        System.out.println ("Compute Time (Nanos):" + CPU);
        System.out.println ("Wait Time (Nanos):" + wait);  System.out.println ("Formula:" + numberofcpu + "*" + targetutilization + "* (1 +" + waittime + "/" +
        Computetime + ")");
    System.out.println ("* Optimal thread Count:" + optimalthreadcount); }/** * Runs the {@link Runnable} over a period defined in {@link #testtime}. Based on Heinz Kabbutz ' ideas * (http://www. javaspecialists.eu/archive/issue124.html). * @param task The runnable under investigation * * public void Start (runnable Task) {Long start =
        0;
        int runs = 0;
            do {if (++runs > 5) {Throw the new IllegalStateException ("Test not accurate");
            } expired = false;
            Start = System.currenttimemillis ();
            Timer timer = new timer ();
                Timer.schedule (New TimerTask () {public void run () {expired = true;
            }}, Testtime);
            while (!expired) {task.run ();
            Start = System.currenttimemillis ()-Start;
        Timer.cancel ();
        while (Math.Abs (start-testtime) > Epsylon);
    CollectGarbage (3);
            private void CollectGarbage (int i = 0; I < times; i++) {System.GC ();
              try {  Thread.Sleep (10);
                The catch (Interruptedexception e) {thread.currentthread (). interrupt ();
            Break }}/** * Calculates the memory usage of a single element in a work queue.
     Based on Heinz Kabbutz ' ideas * (http://www.javaspecialists.eu/archive/Issue029.html). * * @return Memory usage of a single {@link Runnable} element in the thread pools work Queue */public long
        Calculatememoryusage () {blockingqueue<runnable> queue = Createworkqueue ();
        for (int i = 0; i < sample_queue_size i++) {Queue.add (Creattask ());
        Long mem0 = Runtime.getruntime (). TotalMemory ()-Runtime.getruntime (). Freememory ();
        Long mem1 = Runtime.getruntime (). TotalMemory ()-Runtime.getruntime (). Freememory ();
        queue = null;
        CollectGarbage (15);
        MEM0 = Runtime.getruntime (). TotalMemory ()-Runtime.getruntime (). Freememory (); Queue= Createworkqueue ();
        for (int i = 0; i < sample_queue_size i++) {Queue.add (Creattask ());
        } collectgarbage (15);
        Mem1 = Runtime.getruntime (). TotalMemory ()-Runtime.getruntime (). Freememory ();
    Return (MEM1-MEM0)/sample_queue_size;
     /** * Create your runnable task here. * @return An instance of your runnable task under investigation * protected abstract runnable creattask ()

    ;
     /** * Return a instance of the queue used in the thread pool.

    * * @return Queue Instance * * Protected abstract blockingqueue<runnable> createworkqueue (); /** * Calculate Current CPU time. Various frameworks may is used here, and depending on the operating system at use.
     (e.g. * Http://www.hyperic.com/products/sigar).
     The more accurate the "CPU time" measurement, the more accurate the results * for thread count boundaries. * * @return Current CPU time of the current thRead */protected abstract long getcurrentthreadcputime ();
 }

Implementation section

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.lang.management.ManagementFactory;
Import Java.math.BigDecimal;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.util.concurrent.BlockingQueue;

Import Java.util.concurrent.LinkedBlockingQueue; public class Mypoolsizecalculator extends Poolsizecalculator {public static void main (string[] args) throws Interrup 
        Tedexception, Instantiationexception, Illegalaccessexception, classnotfoundexception {
        Mypoolsizecalculator calculator = new Mypoolsizecalculator ();
    Calculator.calculateboundaries (New BigDecimal (1.0),//CPU utilization, 1 is 100% new BigDecimal (100000)); //U need to implement protected long Getcurrentthreadcputime () {return MANAGEMENTFACTORY.GETTHREADMXB
    Ean (). Getcurrentthreadcputime (); }//U need to implement protected Runnable Creattask () {return NEW Asynciotask (); }//U need to implement protected blockingqueue<runnable> Createworkqueue () {return new Linkedblo
    Ckingqueue ();  } class Asynciotask implements Runnable {@Override public void run () {httpurlconnection connection
        = NULL;
        BufferedReader reader = null;
            try {String GetURL = "http://baidu.com";

            URL getUrl = new URL (getUrl);
            Connection = (httpurlconnection) geturl.openconnection ();
            Connection.connect ();

            reader = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
            String Line; 

        while (line = Reader.readline ())!= null) {//Empty Loop}} catch (IOException e) {
                finally {if (reader!= null) {try {reader.close ();
catch (Exception e) {}}            Connection.disconnect ();
 }
    }
}

This piece of code targetqueuesizebytes, do not know what meaning.

2. How to sync between multithreading? There are usually several ways.

The first kind is synchronized.

The second kind of lock

The first two kinds of locks are the way, there is no way to lock. Of course

Atomic, Copyonwrite and so on.

Multithreading at the same time, add locks, we can understand, but read and write, should not add locks. To answer this question, it is necessary to understand why we are multithreaded synchronization? The answer is simple, to keep the data intact. Imagine a thread that writes data to a file and completes it in about a day. A thread reads the file from this file, and it takes about a day, then read the line isconcurrently read a part of the data, has not finished reading, the unread part of the write thread has been modified, read the thread read the modified part. Imagine the value of this data. Integrity is waste data, no use at all. Based on this, read-write threads, write-write threads do synchronization to ensure the integrity of the data. So we throw a few questions

1. What is the principle of synchronized, and what is the performance?

2. Volatile

3. The realization principle of Lock


4. The difference between synchronized and lock.


Let's say the first question, the synchroinzed principle

Synchronized

This is the Java keyword, which isimplemented using monitors. Each Java are associated with a monitor, which athread can lock or unlock.

Only one thread in a time may hold a Lockon a monitor. Any of the other threads attempting to lock this monitor are blockeduntil they can obtain a lock on that monitor. A thread T may lock particular the monitormultiple times. Each unlock reverses the effect of one lock operation.

The synchronized statement computes areference to a object.it then-attempts to perform a lock on that ' s objectsmonitor  D does not proceed further until the lock action Hassuccessfully completed. After the lock action has been performed, thebody to the synchronized statement is executed. If execution of the body Isever completed, either normally or abruptly, a unlock action is automatically Performedon Same monitor.

Othermechanisms, such as reads and writes of volatile variables and the use ofclasses in the Java.util.concurrent, Provide alternative ways ofsynchronized.

From the above text, we can see that the synchronized is implemented by adding a monitor lock on the object, which thread acquires the lock, and which thread can perform. Synchronized automatically releases monitor lock after execution of the code within the range. The thread in the wait set, which was notify, started capturing monitor lock execution.

The two byte code instructions for Monitorenter and Monitorexit are formed before and after the synchronized block. According to the requirements of the virtual machine specifications, in the implementation of Monitorenter instructions, the first attempt to obtain the object's lock, if the lock, the lock counter plus 1, accordingly, in the implementation of MONITOREXIT instructions will be the lock counter 1, when the counter is 0 o'clock, the lock was released.

The synchronized lock has four states in Java 1.6:

Non-lock state, in favor of lock state, lightweight lock state and heavyweight lock state, it will gradually upgrade with the competition situation. Locks can be upgraded but cannot be degraded, meaning that a preference lock is upgraded to a lightweight lock and cannot be degraded to a biased lock.


Bias Lock:


Hotspot's authors have found that in most cases, locks not only have no multi-threaded competition, but are always obtained from the same thread multiple times, in order to allow the threads to obtain a lock at a lower cost and introduce a bias lock. When a thread accesses the synchronization block and acquires the lock, the thread ID of the lock bias is stored in the lock record in the object header and in the stack frame, and the thread does not need to spend the CAS operation to lock and unlock when entering and exiting the synchronization block, but simply test the object header's mark Does Word store a bias lock that points to the current thread? If the test succeeds, indicating that the thread has acquired the lock, and if the test fails, you will need to test to see if the lock-biased identity in Mark Word is set to 1 (indicating that it is currently biased), and if it is not set, use the CAS competitive lock, if set, You try to use CAs to point the tilt lock of the object header to the current thread. preference to lock revocation : Biased locks use a mechanism that waits until the competition arises to release the lock, so a thread that holds a biased lock will release the lock when other threads try to compete for the lock. The preference for lock revocation requires waiting for the global security point (No bytecode is executing at this point in time), it first pauses the thread that owns the biased lock, and then checks whether the thread holding the biased lock is alive, and if the thread is not active, sets the object header to a lock-free State, and if the thread is still alive, A stack with a bias lock is executed, traversing the lock record of the biased object, the lock record in the stack, and mark Word of the object head is either back to the other thread or back to the unlocked or tagged object as a biased lock, and the last wake-up paused thread


Lightweight lock (Lightweight lock)

Lightweight Lock Lock: Before a thread executes a synchronization block, the JVM creates the space in the current thread's stack to store the lock record, and copies the Mark Word in the object header to the lock record, officially called displaced Mark Word. The thread then attempts to use CAs to replace Mark Word in the object header with a pointer to a lock record. If successful, the current thread acquires the lock and, if it fails, indicates that the other thread is competing for the lock, and the current thread attempts to use the spin to acquire the lock. Lightweight Unlock: Lightweight unlock, using the atomic CAS operation to replace displaced Mark word back to the object header, if successful, means no competition occurs. If the failure indicates that the current lock is competitive, the lock expands into a heavyweight lock.



comparison of the advantages and disadvantages of locks

Lock

Advantages

Disadvantages

Applicable scenarios

Bias Lock

Locking and unlocking does not require additional consumption, and the implementation of asynchronous methods is more than a nanosecond-level gap.

If there is a lock competition between threads, it will lead to additional lock-revocation consumption.

Applies to only one thread accessing the synchronization block scene.

Lightweight locks

The competing threads do not block, increasing the response speed of the program.

A thread that does not always have a lock to compete uses a spin that consumes the CPU.

The pursuit of response time.

The synchronization block executes very quickly.

Heavy-weight lock

Thread competition does not use spin and does not consume CPU.

Thread blocking, slow response time.

Pursuit of throughput.

The synchronization block executes more quickly.


Here's a second question:

Volatile

If youare working with muti-threaded programming, the volatile keyword would be moreuseful. When multiple threads a using the same variable, each thread would haveits own copy of the local cache to that variable.

So,when it ' s updating the value, it is actually updated in the local cache not inthe main variable. The other thread which are using the same variabledoesn ' t know anything about the values changed by the another thread.

To avoid this problem, if you declare a variable as volatile, then it won't bestored in the local cache. Whenever thread are updating the values, it isupdated to the main memory. So other threads can access the updated value.

Third question:

Lock


A lock is a thread synchronizationmechanism like synchronized blocks except locks can to more sophisticated Thanjava ' s SYN Chronized blocks, so it isn't like we can get totally rid of thesynchronized keyword.

Fromjava 5 The Package java.util.concurrent.locks contains several lockimplementation, so do not have to implement Y Our own locks, But your willstill need to know how to use Them,and it can still is useful to know the theory behind R implementation.

Lock reentrance

Synchronized blocks in Java are reentrance. This is means, that if a javathread enters a synchronized blocks of code, and thereby take the lock on Themonitor object The B Lock is synchronized on, the thread can enter other Java codeblocks synchronized on the same monitor object. This is example:

public class reentrant{

Public synchronized outer () {

Inner ();

}

Public synchronized inner () {

Do something

}

}

Notice how both outer () and inner () aredeclared synchronized, which in Java are equivalent to a synchronized (this) block. If A thread calls outer () there is no problem calling inner () frominside outer (), since both methods are-synchronized on t He same the monitor object (' this '). If A thread already holds the lock on a monitor object, it has access to allblocks synchronized on the same monitor object . This is called Reentrance. Thethread can reenter any blocks of code for which it already holds the lock.

Lock Fairness

Java ' ssynchronized blocks makes no guarantees about the sequence in which threadstrying to enter them are granted access. Therefore, if many threads areconstantly competing for access to the same synchronized blocks, there is a riskthat one or M Ore of the threads are never granted Access-that access is alwaysgranted to other threads. This is called starvation. To avoid this a lockshould be fair. Since the Lock implementations shown in this text usessynchronized blocks internally, they does not guarantee.


Fourth question:

From the above analysis, we can see that lock is more flexible in writing, while lock introduces lock fairness's concept.




Reference Documentation:

https://my.oschina.net/u/557580/blog/225554

Https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html



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.