Concurrent Programming (1) - Basic

Parallel and concurrent

Parallel: simultaneous execution of multiple tasks. For example, the amount of two parallel tasks CPU core is two.

Concurrency: the number of tasks that can be performed per unit time. If the CPU is a single core, the unit time is 1 second, the number of concurrent tasks that refers executed by the CPU 1 second. Single-core CPU can execute at the same time a thread. That in one second may alternately perform 100 threads. I.e. concurrency is 100.

High concurrency benefits

1, make full use of CPU resources

2, to improve the response time

3, the code can be made modular, asynchronous and simplification

Multithreading considerations

1, thread-safe

2, deadlock

3, too many threads will transition consume server resources, and even downtime

Java multi-threaded

Java thread information print run:

public class Test {
    public static void main(String[] args) {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
        // 打印线程信息
        System.out.println("打印结果:");
        for (ThreadInfo threadInfo : threadInfos) {
            System.out.println(threadInfo.getThreadId() + ":" + threadInfo.getThreadName());
        }
    }
}

/*
 * 打印结果:
 * [6] Monitor Ctrl-Break
 * [5] Attach Listener
 * [4] Signal Dispatcher
 * [3] Finalizer
 * [2] Reference Handler
 * [1] main
*/

Java There are two ways to create threads

Thread class inheritance, and then to implement Runnable Thread run

Thread is an abstraction of the thread, Runnable just an abstract of the task.

The description Thread

Thread related methods

start()

Start a thread. Let the thread into the ready queue waiting for allocation CPU, CPU assigned to run after the call realized () method. start () method can not be called repeatedly reported [otherwise] java.lang.IllegalThreadStateException exception.

run()

The main thread of logic method

yield()

The current thread yields the CPU possession, so that the time can not be set, it will not release the lock resources, it may not hold the lock. You can call the yield method releases the lock after resource. All threads executing yield () is likely to enter the ready state after the operating system will be checked again immediately be executed.

sleep()

Thread sleep time specified, will not release the lock resources.

join()

The specified thread added to the current thread, two threads alternately performed may be combined into execution order. For example, the calling thread B, thread A Join () method, after finished until the thread A, will continue executing thread B.

interrupt()

Logo interrupted thread isInterrupted () default is false, such as a thread calls interrupt () method then the state is set to true, the thread by determining isInterrupted () identifies whether interrupt is set to true, and if so, interrupt threads. Thread.interrupted () method can also be used to determine whether an interrupt flag is set to true, it will eventually interrupt flag is reset to false.

wait()

The thread into the WAITING state, as long as another thread waiting for notification of or interruption will not return.

notify() | notifyAll()

A notice [|] all waiting on this object's thread, to return from the wait method, the premise is returned to the thread gets the lock object. I did not get to lock the thread re-enter the WAITING state.

Thread deadlock state can not be interrupted.

Sharing and collaboration between threads

Built-synchronized lock

Reentrant lock.

It ensures that multiple threads at the same time, only one thread is synchronized method or block, it ensures visibility and exclusive threads of variable access, also known as the built-in locking mechanism.

Object locks and lock classes:

Lock the object is a method for the object instance, or an object instance of the class is the lock on the class object or a class of static methods for the class. Object instances of a class can have many, but each class has only one class object, the object lock a different object instances interfere with each other, but each class has only one class lock.

volatile

Ensure visibility when different threads of variables operation. When a thread modifies the value of a variable, the new value to other thread is immediately visible.

Applicable scene: a thread write, read multiple threads

// volatile多线程写不安全示例
public class TestVolatileSafe {
    private volatile Integer count = 0;

    public void add() {
        count++;
    }

    public static void main(String[] args) throws Exception{
        TestVolatileSafe testVolatileSafe = new TestVolatileSafe();

        new ThreadClass(testVolatileSafe).start();
        new ThreadClass(testVolatileSafe).start();

        Thread.sleep(5000);

        System.out.println(testVolatileSafe.count);// 每个线程对count加1万次,最终结果不是2万
    }
}

class ThreadClass extends Thread {
    private TestVolatileSafe testVolatileSafe;

    public ThreadClass(TestVolatileSafe testVolatileSafe){
        this.testVolatileSafe = testVolatileSafe;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            testVolatileSafe.add();
        }
    }
}

ThreadLocal

ThreadLocal each thread provides a copy of the variable so that each thread at a time to visit is not the same object, thus isolating the multiple threads of data for data sharing.

i.e., by means of a spring ThreadLocal transaction type, to prevent the multi-thread of each thread database connection object is modified.

ThreadLocal method:

void set(Object value);

Object get();

void remove();

protected Object initialValue();

Returns to the initial value of this thread-local variable, which is a protected method, apparently in order to allow subclasses cover design. This method is a method to delay calling, call get () or set (Object) when the execution thread the first time, and only performed once. The default ThreadLocal in direct returns a null.

Description:

ThreadLocalMap static inner class of ThreadLocal, ThreadLocal internal static inner classes have an Entry, Entry static inner class inherits

WeakReference[弱引用]。

ThreadLocalMap is unique to each thread, ThreadLocalMap the key for the ThreadLocal itself, Entry of the key is the thread itself.

ThreadLocal trigger a memory leak:

Strong references: Similar "Object o = new Object ();", as long as there are still strong reference, the garbage collector will never fall recovered reference object instance.

Soft references: is used to describe some, but not as well as with the necessary objects. For soft references associated with an object, the system will take place before the memory overflow exception, these objects will be listed as examples within the scope of a second recycling recovered. If the recovery has not enough memory, memory overflow exception will be thrown. After JDK1.2, it provides SoftReference classes to implement soft references.

Weak references: is non-essential to describe the object, but its intensity is weaker than the soft references, cited weakly associated with an object instance can only survive until the next time garbage collection occurs. When the garbage collector job, regardless of the adequacy of current memory will only recover lost object instance is associated with a weak reference. After JDK 1.2, provided WeakReference classes to implement weak.

Virtual reference: also known as ghost or phantom cited references, it is the weakest one reference relationship. The presence of an object instance is a virtual reference, will not hurt its lifetime, can not be achieved by a phantom reference object instance. The sole purpose of setting an imaginary reference target is associated with a system to receive a notification when the object instance is recovered collector. After JDK 1.2, provided PhantomReference classes to implement virtual reference.

Cause Analysis:

    Thread each maintain a ThreadLocalMap, the key mapping table is ThreadLocal instance itself, is a real need to store the value of Object, that is to say ThreadLocal itself is not stored value, it is just as a key to let the thread gets value from ThreadLocalMap. Careful observation ThreadLocalMap, this map is used ThreadLocal incorporated Key weak, the object is weak references recovered in the GC. Thus, threadlocal When the variable is set to null, no references to any strong threadlocal instance, it will be threadlocal gc recovered. As a result, ThreadLocalMap will appear in the Entry key is null, there is no way to access the key to null Entry of value, if the current thread still delay the end, these key for the Entry of the value null will always exist a strong chain of references: Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value, and this value will never be accessed, so there is a memory leak.

solve:

    Only after the end of the current thread, current thread would not exist stack, strong references disconnect, Current Thread, Map value will all be recovered GC. After the best practice is to not require the use of ThreadLocal variables are calling its remove () method to remove the data.

Waiting / notification mechanism

nofity ()

    Notify a thread waiting on the object, to return from the wait method, but the premise is returned to the thread gets the lock object, the thread does not get a lock to re-enter waiting state.

nodifyAll()

    Notify all waiting on this object's thread

wait()

    This method is called a thread into the waiting state, only to wait another thread or interrupt notification will not return. Will release the lock of the object after a call to wait () method.

wait(long)

    Waiting timeout period, where the parameter is the time in milliseconds, to wait for n milliseconds that is, if there is no time-out notice to return.

wait(long, int)

    For more fine-grained control timeout, you can achieve nanosecond.

Paradigm waiting / notification

    Wait for the party:

        Acquiring an object lock

        If the condition is not met, then call the object's wait () method, after being notified still checking conditions

        Corresponding logical condition is satisfied is executed

    Notify Party:

        To obtain the object lock

        Changing conditions

        Notify all waiting on the object thread

Released five original articles · won praise 0 · Views 119

Guess you like

Origin blog.csdn.net/u010636239/article/details/105131012