Java Fundamentals-concurrency model, base interface, and thread

Source: Internet
Author: User
Java concurrency concepts, base interfaces, and thread

This series of articles mainly on Java concurrency related content, including synchronization, lock, semaphore, blocking queue, thread pool, etc., the overall mind map is as follows:

This paper mainly explains the concurrency model, basic interface, thread base operation and threadlocal application.

Advantages and disadvantages of concurrency

In the case of how to use multithreading, let's take a look at the pros and cons of multithreading concurrency.

Advantages
  • Increase resource utilization
    If you read all the files in a directory, if you use a single-threaded model, most of the time you read files from disk, you wait for the CPU disk to read the data. If the multi-threaded concurrent execution, you CPU can wait IO for the time to do other things, to improve CPU the utilization rate, reduce the waste of resources.

  • Program response speed is good
    Single-threaded model, assuming that a http request takes a significant amount of time to process, other requests cannot send the request to the server. In multithreaded mode, the listener thread passes the request to the worker thread and then immediately returns to the listener to receive the new request, while the worker thread can process the request and send a reply to the client. The apparent response speed is much better than a single-threaded model.

    Disadvantages
  • Complexity of programming
    In the case of multithreading, it is necessary to consider the communication between threads and the access of shared resources, which is relatively more responsible than a single thread.
  • High context switching overhead
    When CPU switching from executing a thread to executing another thread, it needs to store the local data of the current thread, the program pointer, and so on, then load the local data of the other thread, the program pointer, and so on, before the execution begins. This switchover is referred to as a "context switch". CPUexecutes a thread in one context and then switches to another context to execute another thread. Especially when the number of threads is large, this overhead is obvious.
  • Resource consumption
    Threads need to get some resources from the computer while they are running. In addition CPU , the thread also needs some memory to maintain its local stack. It also needs to occupy some resources in the operating system to manage threads

    Concurrency model

    Concurrent systems can be implemented with multiple concurrent programming models. The concurrency model specifies how threads in the system can collaborate to complete the jobs assigned to them. Different concurrency models split jobs in different ways, while collaboration and interaction between threads are not the same.

    Parallel worker

    In the parallel worker model, the delegate ( Delegator ) assigns the incoming job to a different worker. Each worker completes the entire task. Workers work in parallel on different threads, possibly even on different CPUs.

    Assuming that the second-kill activity in the e-commerce system employs a parallel worker model, the logistics of warehousing------------------------------
    In Java applications, the parallel worker model is the most common concurrency model, and java.util.concurrent many of the concurrency utilities in the package are designed for this model.

Advantages
Easy to understand, can add more workers to improve the degree of parallelism of the system
Disadvantages

    • Shared state can be complex
      In the above e-commerce system, because shared workers often need to access some shared data, either in-memory or in a shared database.
      While waiting for access to shared data structures, there is a loss of parallelism between threads waiting for each other. Many concurrent data structures are blocked, meaning that only one or a few threads can access them at any one time. This results in a competitive state on these shared data structures. When executing code that requires access to the shared data Structure section, high competition basically results in some degree of serialization at execution time.
    • Non-state workers
      Rereading the data you need each time will result in slower speeds, especially when the state is stored in an external database.
    • The order of the tasks is indeterminate
      The job execution order is indeterminate and there is no guarantee that the job will be executed first or last. If a first order, b after the order, not according to the time of business logic judgment, can not possibly B before a receipt of goods.
pipelining mode

In pipelining mode, each worker is responsible for only part of the work in the job. When you have completed this part of your work, the worker forwards the job to the next worker. Each worker runs in its own thread and does not share state with other workers. Also known as reactor systems, or event-driven systems.

In the case of seconds, worker a executes the order processing, worker B executes the payment, worker C checks the warehouse, worker D is responsible for logistics, the Division of labor is clear, and the duties are assigned.
In practical applications, the operation may not be carried out along a single pipeline. Because most systems can perform multiple jobs, the job flows from one worker to another depends on the work that the job needs to do. In practice, there may be multiple different virtual pipelines running concurrently.

Jobs may even be forwarded to more than one worker on concurrent processing. For example, a job might be forwarded to the job executor and the job logger at the same time. Illustrates how three pipelines can be completed by forwarding jobs to the same worker (the last worker in the middle pipeline):

Advantages

    • No need to share a state
      There is no need to share state between workers, which means no need to consider all concurrency problems resulting from concurrent access to shared objects

    • Better Hardware Integration
      Single-threaded code often has a better advantage when it comes to consolidating the underlying hardware. First, it is often possible to create more optimized data structures and algorithms when the code can be determined to execute only in single-threaded mode.

    • Reasonable Order of operations
      The concurrency system based on pipeline concurrency model is possible to ensure the order of the jobs in some way. The orderly nature of the job makes it easier to roll out the state of a system at a particular point in time

Disadvantages

    • Very difficult to write
      Fortunately there are some platform frameworks that can be used directly, such as Akka , Node.JS etc.

    • Tracking difficulties
      The biggest disadvantage of the pipelining concurrency model is that job execution is often distributed across multiple workers, and therefore distributed across multiple classes in a project. This makes it difficult to track exactly what code is being executed by a job.

Function-Parallel

The basic idea of function-parallel is to implement the program by function call. Functions can be thought of as proxies agents or actor between functions that can send messages to each other like pipelining models (reactors or event-driven systems).
Functions pass parameters by copying, so no entity can manipulate the data except the receive function. This is necessary to avoid the race of sharing data. It also makes the execution of a function similar to an atomic operation. The execution of each function call is independent of the invocation of any other function.

Runnable, callable, Future, Thread, Futuretask

JavaIn the concurrency, the main Runnable , and Callable Future three interfaces as a basis.

Runnable

The instance wants to be executed by the thread, which can be implemented by the Runnable interface.
。 By instantiating an Thread instance and running itself as a target, you can run the implemented Runnable class without having to create Thread subclasses. In most cases, you should use an interface if you only want to override the run() method without overriding the other Thread methods Runnable . This is important because unless the programmer intends to modify or enhance the basic behavior of the class, you should not create subclasses for that class.

Callable

CallableInterfaces are similar Runnable , and both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.

Future

FutureRepresents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. getyou can only use methods to get the results after the calculation is complete, and if necessary, block this method before the calculation is complete. Cancellation is performed by the Cancel method. Other methods are provided to determine whether the task is completed properly or canceled. Once the calculation is complete, you can no longer cancel the calculation. If you are using for de- Future future<?> but do not provide the available results, you can declare the form type and return null as the result of the underlying task.
The main methods are as follows:

    • cancel(boolean mayInterruptIfRunning)
      An attempt was made to cancel execution of this task.
    • get()
      If necessary, wait for the calculation to complete and then get its results.
    • get(long timeout, TimeUnit unit)
      If necessary, wait for the result to be obtained (if the result is available) after the time given for the calculation to complete.
    • isCancelled()
      Returns true if the task is canceled before it is completed properly.
    • isDone()
      Returns true if the task is completed.
Thread threads are created

In Java , we have 2 ways to create a thread:

    • By inheriting thread the class directly, and then overriding the run() method.
    • Build a Runnable class that implements the interface, and then create a thread class object and pass the Runnable object as a construction parameter
Running processes for threads

We create 5 sub-threads in the main thread, and each child thread initializes the value of number with the constructor to implement the multiplication table within 1-5:

package com.molyeo.java.concurrent;/** * Created by zhangkh on 2018/7/18. */public class ThreadTest {    public static void main(String[] args) {        System.out.println("main thread start");        for (int i = 1; i <= 5; i++) {            Calculator calculator = new Calculator(i);            Thread thread = new Thread(calculator);            thread.start();        }        System.out.println("main thread end");    }}class Calculator implements Runnable {      private int number;     public Calculator(int number) {        this.number = number;    }       @Override    public void run() {        for (int i = 1; i <= 5; i++) {            System.out.printf("%s: %d * %d = %d \n", Thread.currentThread().getName(), number, i, i * number);        }    }}

The program output is as follows:

In Java, each application has at least one thread of execution, and the JVM is responsible for invoking the execution thread of the main () method when the program is run.
The Java program ends when all non-daemon threads are executed. From the output you can also see that after the main program output main thread end , other programs continue to execute until the execution is finished.
It is important to note that if a thread is called System.exit() to instruct the finalizer, then all the threads will end up executing.

Thread break, sleep, set priority

In the following example, the numbergenerator first creates a numbergenetorthread thread, sets the priority, cycles through the thread, prints out the Number until 5 milliseconds after the main thread calls the interrupt () method to break it, numbergenetorthread thread it jumps out of while Loop. The first call to the method isinterrupted () Returns a value of true , indicating that the thread has been interrupted.
Note that the interrupt () method tests that the interrupt state of a thread is also purged by the method when it has been interrupted. In other words, if the method is called twice in a row, the second call returns false . You can open the following comments to test.

Package com.molyeo.java.concurrent;/** * Created by Zhangkh on 2018/8/23. */public class ThreadTest2 {public static void main (string[] args) throws Interruptedexception {Thread Numberg        Enetorthread = new Numbergenerator (0);        Numbergenetorthread.setpriority (thread.max_priority);        Numbergenetorthread.start ();        Thread.Sleep (5);        Numbergenetorthread.interrupt ();        System.out.println ("First interrupt,isinterrupted=" + numbergenetorthread.isinterrupted ());//Thread.Sleep (5);// Numbergenetorthread.interrupt ();//System.out.println ("second interrupt,isinterrupted=" + Numbergenetorthread.    Isinterrupted ());    }}class Numbergenerator extends Thread {private int number;    public numbergenerator (int number) {this.number = number; } @Override public void Run () {while (!isinterrupted ()) {System.out.println ("number is" + Numbe            R);        number++; } System.out.println ("Numbergenerator thread,isinterrupted= "+ this.isinterrupted ()); }}

Part of the program output is as follows:

number is 96number is 97NumberGenerator thread,isInterrupted= truefirst interrupt,isInterrupted=true
ThreadLocal

Definition and function
ThreadLocalCalled Thread-local variables, not to solve the problem of multi-threaded access to shared objects, because if you ThreadLocal.set() put in a multi-threaded shared object, the thread through the Threadlocal.get () method to get the shared object itself, there is still a problem of concurrent access. It is held separately by each thread, mainly providing methods for keeping objects and avoiding parameter passing to facilitate access to objects.

    • Each thread has its own ThreadLocalMap class object, which can hold its own objects into it, and the threads can access their objects correctly.
    • The use of a common ThreadLocal static instance as a key reference to a different object is saved to a different thread ThreadLocalMap , and then the thread executes all the way through the static instance to get the object that it was ThreadLocal saved by get() itself, avoiding the hassle of passing the object as a parameter.

While the program is running, each thread keeps an implicit reference to its copy of the thread's local variables, as long as the thread is active and the ThreadLocal instance is accessible, and all copies of its thread-local instance are garbage collected after the threads have disappeared (unless there are other references to those replicas).

Use the example
below we create an instance of ThreadLocal stringlocal , setting its value to the current thread name, respectively, in the main thread and the child thread. Looking at the results of the output, you can see that the threads are not interfering with each other and outputting their own set values.

package com.molyeo.java.concurrent;/** * Created by zhangkh on 2018/8/24. */public class ThreadLocalDemo {    public static void main(String[] args) throws InterruptedException {        ThreadLocal<String> stringLocal = new ThreadLocal<String>();        stringLocal.set(Thread.currentThread().getName());        System.out.println(String.format("threadName=%10s,threadLocal valaue=%10s",Thread.currentThread().getName(),stringLocal.get()) );        Thread thread1 = new Thread() {            public void run() {                stringLocal.set(Thread.currentThread().getName());                System.out.println(String.format("threadName=%10s,threadLocal valaue=%10s",Thread.currentThread().getName(),stringLocal.get()) );            }        };        thread1.start();        thread1.join();        System.out.println(String.format("threadName=%10s,threadLocal valaue=%10s",Thread.currentThread().getName(),stringLocal.get()) );    }}

The program output is as follows:

threadName=      main,threadLocal valaue=      mainthreadName=  Thread-0,threadLocal valaue=  Thread-0threadName=      main,threadLocal valaue=      main

Source Code Implementation
ThreadLocalThere are 3 member variables

private final int threadLocalHashCode = nextHashCode();private static AtomicInteger nextHashCode = new AtomicInteger();private static final int HASH_INCREMENT = 0x61c88647;private static int nextHashCode() {    return nextHashCode.getAndAdd(HASH_INCREMENT);}

nextHashCodeis a static variable, which is a ThreadLocal HASH_INCREMENT static constant, only the threadLocalHashCode ThreadLocal variable of the instance.
When you create ThreadLocal an instance of a class, assign the value ThreadLocal of the next hashCode value of the class to the nextHashCode instance threadLocalHashCode , and then nextHashCode increase the value HASH_INCREMENT . The instance variable threadLocalHashCode is final used to distinguish between different ThreadLocal instances.
ThreadLocalstringLocalwhen the method is called set() when the instance is created,

public void set(T value) {    Thread t = Thread.currentThread();    ThreadLocalMap map = getMap(t);    if (map != null)        map.set(this, value);    else        createMap(t, value);}

Gets the current thread, which is the main thread, and then calls the method based on the thread instance. getMap() ThreadLocalMap
The getMap() methods are as follows:

ThreadLocalMap getMap(Thread t) {    return t.threadLocals;}

getMap()The method directly returns the member variable of the thread threadLocals , where the threadLocals variable is an instance of the ThreadLocalMap class and ThreadLocalMap is ThreadLocal the inner class.
If map there is a member variable (the current thread threadLocals ), the data is written to the ThreadLoclMap store for the data Entry .
ThreadLocalMapThe set method is as follows:

private void set(ThreadLocal<?> key, Object value) {    Entry[] tab = table;    int len = tab.length;    int i = key.threadLocalHashCode & (len-1);    for (Entry e = tab[i];         e != null;         e = tab[i = nextIndex(i, len)]) {        ThreadLocal<?> k = e.get();        if (k == key) {            e.value = value;            return;        }        if (k == null) {            replaceStaleEntry(key, value, i);            return;        }    }    tab[i] = new Entry(key, value);    int sz = ++size;    if (!cleanSomeSlots(i, sz) && sz >= threshold)        rehash();}

Which is Entry defined as follows

static class Entry extends WeakReference<ThreadLocal<?>> {    Object value;    Entry(ThreadLocal<?> k, Object v) {        super(k);        value = v;    }}

keyAs an ThreadLocal instance, the value is a user-defined specific object value.

If map (the current thread's member variable threadLocals ) does not exist, an instance is created and ThreadLocalMap associated with the thread's member variables threadLocals . Where ThreadLocalMap the instance is, that is key this , the threadlocal instance stringLocal , the value is a user-defined concrete object value.

void createMap(Thread t, T firstValue) {    t.threadLocals = new ThreadLocalMap(this, firstValue);}

In general, ThreadLocal the function is to provide local variables within the thread, which function in the life cycle of the threads. Function: Provide a common variable within a thread (such as the user information for this request), reduce the complexity of the passing of some common variables within the same thread, or provide a private copy of the variable for the thread, so that each thread can modify its own copy of the variable arbitrarily. Without affecting other threads.

This paper mainly explains the concurrency model, basic interface, thread base operation and threadlocal application.

This article references

Java 7 Concurrency Cookbook

http://ifeve.com/concurrency-modle-seven-week-1/

/HTTP

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.