High concurrency Java programming Learning Summary

Here Insert Picture Description
1, Why? Use thread pool
Sometimes, the system needs to handle a lot of requests execution time is very short, if each request to open a new thread, the system will constantly be creating and destroying threads, sometimes spent creation and time on the destruction of threads longer than real time thread execution.
And when too many threads, the system may not be able to stand it.
Use the thread pool to solve some major problems:
by reusing the thread pool threads, each thread to reduce the performance overhead of creation and destruction.
Thread some maintenance and management, such as the timing of the start cycle execution, concurrent control and so on.

2, threadpoolexecutor threads in the pool, each of the parameters used to do?
Executor is an interface with the basic thread pool should be relevant to deal with him.

Executor interface is very simple, only execute a method.

ExecutorService is sub-interface Executor, an increase of some commonly used control method of thread after thread pool is largely the use of these methods.

AbstractExecutorService is an abstract class, ThreadPoolExecutor is the realization of this class.

ThreadPoolExecutor parameters:

ThreadPoolExecutor mExecutor = new ThreadPoolExecutor (corePoolSize, // core number of threads
maximumPoolSize, // maximum number of threads
keepAliveTime, // idle thread survival time
TimeUnit.MILLISECONDS, // time unit
new LinkedBlockingDeque (), // thread queue
Executors.defaultThreadFactory () // thread factory
new AbortPolicy () // queue is full, but more than the current number of threads exception handling strategy when the maximum number of threads
);
corePoolSize:
a core number of threads, the default core thread in the case would have been alive, even in the idle state keepAliveTime not subject to restrictions exist. Unless allowCoreThreadTimeOut set to true.
maximumPoolSize:
The maximum number of threads in the thread pool can accommodate. More than this number of threads will be blocked. When the task queue is not set LinkedBlockingDeque size, this value is invalid.
keepAliveTime:
non-core thread idle time, more than this time will be recovered.
unit
designated keepAliveTime units, such as TimeUnit.SECONDS. When set to true allowCoreThreadTimeOut take effect on corePoolSize.
workQueue

  1. Task queue thread pool
    used, there are three queues, SynchronousQueue, LinkedBlockingDeque, ArrayBlockingQueue.
    threadFactory
    thread factory, providing functionality to create a new thread. ThreadFactory is an interface, only one method

interface a ThreadFactory {public
the Thread newthread (the Runnable R & lt);
}
can be customized by the attributes of threads thread factory. The factory default is:

static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;

DefaultThreadFactory() {
SecurityManager var1 = System.getSecurityManager();
this.group = var1 != null?var1.getThreadGroup():Thread.currentThread().getThreadGroup();
this.namePrefix = “pool-” + poolNumber.getAndIncrement() + “-thread-”;
}

public Thread newThread(Runnable var1) {
Thread var2 = new Thread(this.group, var1, this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
if(var2.isDaemon()) {
var2.setDaemon(false);
}
if(var2.getPriority() != 5) {
var2.setPriority(5);
}
return var2;
}
}
RejectedExecutionHandler
RejectedExecutionHandler也是一个接口,只有一个方法

interface RejectedExecutionHandler {public
void rejectedExecution (the Runnable var1, var2 the ThreadPoolExecutor);
}
when the resources all threads in the pool have been used to add new thread is rejected, the call rejectedExecution RejectedExecutionHandler method.

4, talk about the rules of the internal thread pool using
a thread pool thread to perform the task queue with the rules of a great relationship.
Here we assume the task queue no size limit:
If the number of threads <= the number of kernel threads, then directly start a kernel thread to perform the task, not placed in the queue.
If the number of threads> core number of threads, but <= maximum number of threads, and the task queue is LinkedBlockingDeque time, more than the number of kernel threads on the task queue task queue.
If the number of threads> core number of threads, but <= maximum number of threads, and the task queue is SynchronousQueue when the thread pool creates a new thread to perform tasks that would not have been placed in the job queue. These threads are non-core thread, after the task is completed, the idle time reaches the timeout will be cleared.
If the number of threads> core number of threads, and> maximum number of threads, when the task queue is LinkedBlockingDeque, will exceed the core thread of tasks on the task queue queue. That is, when the task queue is LinkedBlockingDeque and no size limit, set the maximum number of threads in the thread pool is ineffective, his core number of threads does not exceed a maximum number of threads.
If the number of threads> core number of threads, and> maximum number of threads, when the task queue is SynchronousQueue time, because the thread pool refused to add the task and throw an exception.
When the limited size of the task queue
when LinkedBlockingDeque filled, the new task will directly create a new thread to execute, when the number of threads created exceeds the maximum number of threads will throw an exception.
SynchronousQueue no limit to the number. Because he does not keep these tasks, but directly to the thread pool for execution. When the number of tasks exceeds the maximum number of threads will directly throw an exception.

  1. atomicinteger common method
    public final int getAndSet (int newValue) // and returns to AtomicInteger provided newValue added oldValue
    public Boolean of compareAndSet Final (Expect int, int Update) // if the input and expected values set equal, and returns to true / to false
    public Final int getAndIncrement () // add 1 AtomicInteger of atoms before and returns the value of the current self-energizing
    public final int getAndDecrement () // Save for 1 AtomicInteger atom and before returning from the subtraction value
    public int getAndAdd Final (int Delta) before adding the delta value to // AtomicInteger atoms and a returning value
    public int Final incrementAndGet () // add to AtomicInteger atom. 1 and return a value obtained by adding. 1
    public int Final decrementAndGet () // Save for AtomicInteger atoms and returns the value 1 minus 1
    public int Final addAndGet (int delta) // specified to AtomicInteger atoms plus a delta value and a value after adding
    6, threadlocal used it? How to use?
    As early version of the JDK 1.2 provides java.lang.ThreadLocal, ThreadLocal provide a new way to solve the problem of concurrent multi-threaded programs. Using this tool can be very simple class to write a beautiful multi-threaded programs.
    ThreadLocal it is tempting too literally, it assumed that a "thread-local."
    In fact, ThreadLocal is not a Thread, but Thread local variables, perhaps named it easier to understand some of the ThreadLocalVariable.
    ThreadLocal variables in each thread creates a copy, then each thread can access its own internal copy of the variable.
    ThreadLocal thread is a local copy of the variable tools. Mainly for the private copy of the object stored in the thread and the thread to do a mapping, variable between individual threads without disturbing each other, in a highly concurrent scenarios can be achieved without state calls, especially for dependent variable values each thread does not make sense complete scenes operations.

the ConnectionManager {class
Private static Connection Connect = null;
public static Connection the openConnection () {
IF (Connect == null) {
Connect the DriverManager.getConnection = ();
}
return Connect;
}
public static void closeConnection () {
IF (Connect =! null)
connect.close ();
}
}
Consider a database link management class, use this code in a single thread is no problem, but if you use multiple threads do? Obviously, the use of multiple threads exist in the thread safety problems: First, there are two methods were not synchronized, it may create openConnection connect several times in the process; second, because the connect is shared variables, in place of the inevitable need to connect calls to protect synchronous thread-safe, because it is likely a thread using the connect database operation, and another thread calls closeConnection close links.
So for thread safety considerations must be two methods to synchronize this code, and place the call to connect the need for synchronization.

This will greatly affect the efficiency of program execution, because a thread when using the connect database operation, other threads wait.

So we have to carefully analyze this problem, which in the end or need to connect local variables to share? In fact, it is not required. If each thread has a connect variable, variable access to connect between each thread is actually no dependencies, that do not care whether a thread other threads to connect this was modified.
Here, there may be a friend thought that since this variable does not need shared between threads can be processed directly so, create a database link if the specific use of each method requires a database connection, and then re-release method call is completed this connection. For example, the following:

class ConnectionManager {
private Connection connect = null;
public Connection openConnection() {
if(connect == null){
connect = DriverManager.getConnection();
}
return connect;
}

public void closeConnection() {
    if(connect!=null)
        connect.close();
}

}

class Dao{
public void insert() {
ConnectionManager connectionManager = new ConnectionManager();
Connection connection = connectionManager.openConnection();

    //使用connection进行操作
     
    connectionManager.closeConnection();
}

}
This treatment did not have any problems, since the connection each time the internal methods created, the thread safety problem does not exist naturally between threads. But it would have a fatal effect: causes the server to the pressure is very large, and seriously affect program execution performance. Because the method needs to open and close the database connection frequently, so endless seriously affect the efficiency of program execution, it may also lead to enormous pressure on the server.

Then the use of ThreadLocal in this case, but right then, because ThreadLocal each thread is created in a copy of the variable, that is, each thread of the interior will have a variable, and can be used anywhere in the internal thread, independently of each other between the threads, so that there is no thread-safety issues, it will not seriously affect program execution performance.

Note, however, said that although the ThreadLocal can solve the above problem, but because in each thread creates a copy of it to consider its consumption of resources, such as memory usage than not using ThreadLocal larger.

From the above chart, we have a glimpse of ThreadLocal core mechanism:
each has an internal thread Thread Map.
Map inside thread local storage objects (key) and a copy of the thread variable (value)
variable, however, Thread internal Map is maintained by the ThreadLocal, ThreadLocal by the thread responsible for getting and setting the value of the map.
So for the different threads, each time you get a copy of the value, other threads can not get to a copy of the current thread's value, a copy of the form isolation, without disturbing each other.

  1. ThreadLocal class provides several core following methods:
    Method name Function
    public T get () get () method used to obtain the current thread's copy of the variable value of the
    copy of the variable public void set (T value) set () method is used to save the current thread's value
    public void remove () remove () method removes the current copy of the future value of the variable
    8, what difference programs, processes, threads that give realistic examples?
    program (program): is a set of instructions. Program can not be executed independently, only to be loaded into memory to perform the system allocates resources for it.

Process (Process): As noted above, the implementation of a program called process. Process is an independent unit of resource allocation system, each process occupies a particular address space. Program is static text description of the process, the process is dynamic activities program order execution within the system.

Thread (Thread): a "single continuous flow of control" process. CPU thread scheduling and allocation is the basic unit is smaller than the basic unit of the process can be run independently, also known as lightweight process. Thread can not exist independently, it must be attached to a process. A process can include a plurality of parallel threads, one thread is certainly a part of the process. Java Virtual Machine allows an application to concurrently execute multiple threads. For example: If a workshop is a program, an ongoing task workshop production is a process, each worker engaged in different jobs in the workshop is a thread.

The following code, in fact, there are several threads running:

public static void main(String[] argc) throws Exception {
Runnable r = new Thread6();
Thread t = new Thread(r, “Name test”);
t.start();
}

Two: threads t and main () method (the main thread).

9, the state of the thread
thread usually has five states, create, ready, running, blocking and death state.

Case of obstruction is divided into three types:

Waiting for blocking: running thread execution wait () method, the thread releases all resources occupied, JVM will thread into the "wait pool". After entering this state, can not be automatically wake up, we must rely on other thread calls notify () or notifyAll () method to wake up, wait a class method object

Synchronous blocking: threads running at the time of acquiring synchronization lock object, if the synchronization lock is occupied by another thread, the thread into the JVM will "lock pool".

Other blocking: a thread of execution sleep () or join () method, or issue the I / O request, the JVM will set the thread is blocked. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again. Thread class method sleep.

New state (New): create a new thread object.

Ready state (Runnable): After the thread object is created, other thread calls the start () method of the object. The state of the thread runnable threads in the pool is located, has become runnable, waiting to acquire the right to use the CPU.

Running state (Running): ready state of the thread gets the CPU, executes the program code.

Blocked (Blocked): the thread is blocked for some reason to give up the right to use CPU temporarily stops running. Until the thread into the ready state, a chance to go running.

Death state (Dead): thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

10, to talk about: the difference between sleep, yield, join, wait method
sleep () method to specify the time to wait, it allows the currently executing thread is suspended within a specified period of time, into the blocked state, the method can not only make other same priority or high priority threads get a chance to execute, but also allows low-priority thread gets the opportunity to perform. But the sleep () method does not release the "lock flag", meaning that if there are synchronized sync block other threads still can not access the shared data. Acting on the thread

To Thread.sleep () to suspend execution of the thread, the thread scheduler to put the CPU.

Thread.sleep () method is a static method, it is suspended currently executing thread.

There are two methods Java sleep, a parameter is only one millisecond, and another nanosecond two milliseconds of parameters.

Unlike the wait method, sleep method does not release the lock

If another thread a thread interrupted sleep, sleep method throws Interrupted Exception.

After waking dormant threads can not be guaranteed to get CPU, it will first enter the ready state, competing with other threads CPU.

There is a error-prone place, when you call t.sleep () when the thread pauses t. This is wrong, because Thread.sleep is a static method, it will make the current thread instead of thread t go to sleep.

join (): current thread to wait, the thread calling this method ends before proceeding. Such as: call the main method t.join (), that the main method to enter the blocked state at this time, such as t-threaded execution has been completed, the main method and then return to the ready state, ready to continue.

join meaningful method must be called after the thread start method is called. This is also very easy to understand: If a thread did not start, that it will not be synchronized. Acting on the thread

11, wait, notify, notifyAll method is defined in the Thread class do? What role are?
wait (), notify (), notifyAll () does not belong to the Thread class, but belong to the Object class, which means that each object has a wait (), notify (), notifyAll () function.

Each object has a lock because the lock is on the basis of each image, and wait (), notify (), notifyAll () are associated with the lock method.

Effect of three methods are:

wait: causes the current thread to wait to enter the block until another thread invokes the object's notify () method or the notifyAll () method.
The current thread must own this object's monitor (Object lock). The thread releases ownership of this monitor and waits until another thread by calling

notify method, or a method notifyAll notification thread on this monitor object waits to wake up. The thread will wait until then to regain ownership of the monitor to continue.

notify: wake up a single thread monitor on this object (Object lock) waits. If all threads are waiting on this object will be selected wake up one thread. Until the lock on this object for the current thread to give up, to continue with the thread to be awakened. This method should only be used as the owner of this object monitor thread to call. "The current thread must own this object's monitor" and "This method should only be used as a thread of this object's monitor to call the owner," explained wait method and notify method must be performed within a sync block, i.e. synchronized (within the obj).

notifyAll: wake up all the threads on this object's monitor (Object lock) to wait.
Thank you for attention! For more information plus qq1723082823

Guess you like

Origin blog.csdn.net/yxxylucy/article/details/92700393