"Java concurrent programming art" notes

The method of reducing context switching: P3
. 1, no lock concurrent programming;
2, CAS algorithm;
3, using a minimum thread;
4, using coroutine;

A common method to avoid deadlock: P6
. 1, to avoid a plurality of threads simultaneously acquire the lock;
2, to avoid a plurality of threads simultaneously occupy resources in the lock, a lock try to ensure that only occupies one resource;
3, try to use the time lock, using lock.tryLock (timeout) instead of using the internal locking mechanism;
4, for database locks, locking and unlocking must be a database connection, otherwise the situation will unlock failure occurs;

The processor implemented method of operating atomic: P17
. 1, a first lock mechanism by a bus to ensure atomicity;
2, the second locking mechanism by the cache to guarantee atomicity;

java implementation of atomic operations: P18
. 1, using the CAS cycle to achieve an atomic operation;
2, a lock mechanism atomicity;

Communication mechanism between threads: shared memory and message passing; of P21

JMM: java memory model; P22

Reordering Category: P23
. 1, compiler optimizations reordering;
2, reordering set of instructions in parallel;
3, a reordering of the memory system;

Sequential consistency memory model characteristics: P32
1, a thread in all operations must be performed in program order;
2, (regardless of whether the program synchronization) that all threads can only see a single sequence of operations performed. In sequential consistency memory model, each operation must be performed and the atom immediately visible to all threads;

Concurrent programming model classification: P24
. 1, Sequential Consistency memory model;
2, Java memory model;

Characteristics volatile variables: p39
. 1, visibility;
2 atomicity; having no atomic volatile ++;

java communication between threads: P54
. 1, thread A write volatile variables, then thread B reads the volatile variables;
2, A write volatile variable thread, with the thread B then updates the CAS volatile variables;
. 3, thread A with CAS updating a volatile variable, then thread B with CAS update this volatile variables;
. 4, CAS a thread with a volatile variable update, then thread B reads the volatile variable;

java线程状态:P87
new、runnable、blocked、waitting、time_watting、terminated;

When the non-Daemom thread does not exist a java virtual machine, java virtual machine will exit. When the java virtual machine exit Daemom thread finally block will not execute when building Daemom thread, you can not rely on the contents of the finally block to ensure that the logic shut down or clean up resources .P91

P92: many statements throws InterruptedException methods (such as Thread.sleep (long millis) method) before these methods throw InterruptedException, java virtual machine to interrupt the thread flag to clear, and then throws InterruptedException.

P95: suspend () method after the call, the thread will not release the resources already occupied (such as locks), but the occupants of resources go to sleep easily lead to deadlock. stop () method at the end of a thread does not guarantee resources thread is normal release, the thread is usually not given the opportunity to complete the work release resources, thus causing the program may under uncertainty.

The security thread is terminated: P95
1, interrupt status; interrupt ();
2, control boolean variable;

Wait / notification mechanism (P99): A refers to a thread calls the object O wait () method enters a wait state while another thread object O B calls notify () or notifyAll after () method, thread A notified () method returns the object from the wait, and further subsequent operations;

Call wait (), notify (), notifyAll () should be noted: P100
1, call wait (), notify (), notifyAll () must first call to lock the object;
2, call the wait () method, the thread state has waitting becomes running, and the current thread into the object queue;
. 3, notify () or notifyAll () method is called after, still without waiting thread () returns from wait, call the notify () or notifyAll () thread releases the lock of the method, the thread waits for a chance () return from the wait;
. 4, Notify () method waits for a waiting thread waiting queue moves from queue synchronization queue, and notifyAll () wait sucked All threads waiting in the queue waiting queue moves from the synchronous queue, the state is moved by the thread programming waitting blocked;
. 5, from the wait () method returns the premise is to obtain a calling object lock.

Pipeline input / output streams: P102
medium 1, the main thread for data transmission between the transmission of the memory;
2, implementation: PipedOutputStream, PipedInputStream, pipedReader, PipedWriter , for the first two bytes, the latter two character-oriented ;

The Thread.join (): P103
. 1, meaning: only () Returns the current thread waits A thread from the thread after termination Thread.join;
2,

Thread Pool (P114) nature: the use of a thread-safe work queue worker threads and connections client thread, the client thread into a work queue task after return, while the worker thread is continuously removed from the work queue work and executed. When the work queue is empty, all the worker threads are waiting on the work queue, when there are client thread has submitted a notice to any task a worker thread, with a large number of tasks are submitted, more workers thread will be awakened.

Lock Interface: P120
characteristics: P121
1, non-blocking attempt to acquire the lock; the current thread tries to acquire the lock if the lock is not the time to get other threads, which successfully obtain and hold the lock;
2, can acquire the lock interrupted ; synchronized with different threads can acquire a lock to respond to the interrupt, when the acquired lock the thread is interrupted, the interrupt will be raised, while the lock is released.
3, time-out to acquire the lock; perhaps lock before the specified deadline, if the deadline is still unable to acquire the lock is returned.

Queue synchronizer (AbstractQueuedSynchronizer) P121;

Template provides a method of synchronizing classification: P122
. 1, like exclusive acquire and release synchronization state;
2, shared acquire and release synchronization state;
3, query thread synchronization waiting queue;

Java classes atomic operations: java.util.concurrent.atomic package (referred Atomic packet) P182
. 1, atomic update type: P182
. 1) to update the base class atom P182;
A) An AtomicBoolean is: Boolean atomic update;
B) of AtomicInteger: atomic update the entire type;
C) AtomicLong: update atoms long integer;
2) update the array atoms P184;
a) AtomicIntegerArray: atomic update integer array, the elements;
B) AtomicLongArray of: updating atoms long integer array elements;
C) AtomicReferenceArray with the: atomic update reference type array of elements;
3) update the reference atom P185;
a) AtomicReference,: update the reference type atom;
B) AtomicRefererceFieldUqdate: atomic update type in the reference field;
C) An AtomicMarkableReference: atomic update the reference flag with the type;
4) update properties atoms P187;
a) AtomicIntegerFieldUqdat: atomic update field shaping updater;
B) AtomicLongFieldUqdat: atomic updates length field shaping updater;
C) an AtomicStampedReference: atomic update version number with a reference type;

Write lock: ReentrantReadWriteLock with
. 1, write lock maintains a lock, comprising a read lock and a write lock; the P140
2, a write lock is reenter the exclusive lock; P143;
. 3, a read lock is supported weight enter the shared lock; P144
4, lock downgrade: refers to the write lock to read lock demotion, refers to hold on (currently owned) write locks, read locks to get in, and then release the write lock (before holding any) of process. P145

LockSupport: P146
. 1, at the beginning of a park LockSupport defines a set of methods used to block the line of the current thread, and unpark (Thread thread) method to wake a thread is blocked;


Object Monitor Method: P147
the wait (), the wait (Long timeout), Notify (), notifyAll ();

Condition: P148
. 1, Condition dependent on Lock objects;
2 first acquires the lock before calling the method: Lock.lock ();
. 3, Lock (synchronizer) has a plurality of synchronous queue and waiting queue;
4, is realized Condition internal type synchronizer, each instance can access condition provided by the synchronous method, each corresponding to a reference condition has belongs synchronizer;

ConcurrentHashMap: P155 thread safe and efficient HashMap
1, do not use HashMap reasons P155 of concurrency: in a multithreaded environment, use HashMap be put action will cause an infinite loop, resulting in CPU utilization close to 100%, it is not in concurrency use HashMap. When performed concurrently HashMap put operation may cause an infinite loop, because the cause of the HashMap multithreaded Entry list data structure to form an annular, ring data structure once formed, the next node Entry never empty, will produce an endless loop Get Entry;
2, HashTable P156: HashTable using synchronized to ensure the security thread, but the thread in the fierce competition of the HashTable very inefficient;
. 3, of ConcurrentHashMap P156: lock with segment technology to improve efficiency;
. 1) is made of ConcurrentHashMap segment array of structures and HashEntry an array of structures;
2) Segment: reentrant lock; HashEntry: for storing key data;
ConcurrentLinkQueue: P161 thread safe queue
1, ConcurrentLinkQueue an unbounded thread-safe queue based on linked nodes, using the FIFO rule sort the nodes, using the "wait-free" algorithm (i.e. CAS algorithm) to implement the algorithm with some modifications on the Michel & Scott algorithm;
2, queues P162: queues is to add enqueue node to the tail of the queue.
Queues mainly do two things:
1) the node is arranged to enqueue the next node queue tail current node;
2) update the tail node if the next node tail node is not empty, then the team is set to tail node node if the next node tail node is empty, then the team node is arranged next node tail, so the tail node not always tail node;
3, a queue P165: returns a node element from the queue, and references to the empty node pair element;
blocking queue P167 for
. 1, two blocking queue is a queue support additional operations. Two additional supports blocking operation of insertion and removal methods;
2, the Java blocking queue Lane 7: P168
. 1) ArrayBlockingQueue with: an array of structures bounded blocking queue; FIFO;
2) a LinkedBlockingQueue: a a linked list structure consisting bounded blocking queue; FIFO;
. 3) a PriorityBlockingQueue is: a support prioritization unbounded blocking queue; acquisition delay support element,
. 4) a DelayQueue: using a priority queue implementation unbounded blocking queue;
5) SynchronousQueue: an storing blocking queue element;
. 6) LinkedTransferQueue: unbounded blocking queue consisting of linked list structure consisting of;
. 7) LinkedBlockingDeque with: a a list structure consisting of a bidirectional blocking queue;
Fork / the Join frame P175: is java7 provided a frame for performing tasks in parallel, is a big task to task is divided into several small, to obtain a large frame final summary results of the task results after each small task.
1, work-stealing algorithm P176: refers to a thread queue stolen from other tasks to perform, usually double-ended queue, the task thread never get stolen mandate from the head double-ended queue, the task thread never steal from the double-ended tail of the queue to take the task execution;
2, ForkJoinPool by the PorkJoinTask and ForkJoinThread array of arrays, ForkJoinTask responsible for an array of programs will be submitted to the store ForkJoinPool task, and ForkJoinThread array responsible for carrying out these tasks; P179
3,

Java tools Concurrency:
. 1, P189 CountdownLatch: CountdownLatch allow one or more threads waiting for other threads to finish;
2, a CyclicBarrier P191: literally be recycled (Cyclic) barrier (Barrier), it needs to be done is to allow a group of threads reach a barrier (also called synchronization point) is blocked when it until the last thread reaches the barrier, the barrier will open the door, all the barriers blocking will continue to run;
3 difference, CountdownLatch and the CyclicBarrier P195: CountdownLatch counter can only be used once, and may be used CyclicBarrier counter reset () method to reset. Therefore CyclicBarrier can handle more complex business scenario;
. 4, P196 Semaphore: Semaphore (semaphore) is used to control the number of threads simultaneously access a specific resource, it is by coordination of the various threads to ensure proper use of public resources;
. 5, Exchanger tool exchanging data between threads P198: exchanger is a utility class for collaboration between threads, for data exchange between threads;
1) by a thread exchange method for exchanging data, a first execution thread exchange, it will wait until the second thread also performs exchange;
thread pool:

Executor frame
1, task. P209 Callable or Runnable interface comprises an interface;
2, mission. How many Executor implementation mechanisms including core tasks, as well as inherited from the Executor ExecutorService interface. Two key ExecutorService class implements the interface (the ThreadPoolExecutor and a ScheduledThreadPoolExecutor);
. 3, asynchronous computation results. It includes an interface and implementation FutureTask Future Future interface class;

Executor framework members: P211 ThreadPoolExecutor, ScheduledThreadPoolExecutor, Future interfaces, Runnable interfaces, Callable interfaces and Executors.
1, ThreadPoolExecutor: P211 ThreadPoolExecutor usually be created using factory classes The Executors;
1) FixedThreadPool: using a fixed number of threads. In order to apply to meet the needs of resource management, and the need to limit the number of threads of the current scenario for heavier server load.
ExecutorService newFixedThreadPool static public (int nThreads);
public static ExecutorService newFixedThreadPool (int nThreads, a ThreadFactory threadFactory);
2) SingleThreadExecutor: using a single thread. To apply to ensure the implementation of each task order, and at any point in time, there will be multiple threads are active scene.
ExecutorService newSingleThreadExecutor static public ();
public static ExecutorService newSingleThreadExecutor (ThreadFactory threadFactory);
3) CacheThreadPool: create a new thread if necessary. CacheThreadPool is unbounded thread pool size for asynchronous tasks to perform many of the short-term program of small, relatively light or attached to a server.
ExecutorService newCacheThreadPool static public ();
public static ExecutorService newCacheThreadPool (a ThreadFactory threadFactory);
2, a ScheduledThreadPoolExecutor: a ScheduledThreadPoolExecutor P211 factory classes typically used to create the Executors;
. 1) a ScheduledThreadPoolExecutor: Create a fixed number of threads. For applications that require multiple cycles to perform background tasks, in order to meet the needs of resource management and to limit the number of background threads with user scenarios.
static ScheduledExecutorSevice newScheduledThreadPoolExecutor public (int corePoolSize);
public static ScheduledExecutorSevice newScheduledThreadPoolExecutor (int corePoolSize, ThreadFactory threadFactory);
2) SingleThreadScheduledExecutor: Create a fixed number of threads. For applications that require a single background thread to perform periodic tasks, and the need to ensure that the application and implementation of the various scenarios task order.
public static ScheduledExecutorSevice newSingleThreadScheduledExecutor ();
ScheduledExecutorSevice newSingleThreadScheduledExecutor static public (a ThreadFactory threadFactory);
. 3, Future interface: P222 Future Future interface and implementation of the interface class to determine the result FutureTask asynchronous computation.
<T> Future <T> Submit (a Callable <T> Task);
<T> Future <T> Submit (the Runnable <T> Task, T Result);
Future <T> Submit (the Runnable Task);
. 4, the Runnable interface, and Callable Interface: P222 Runnable interface and the interface implementation class Callable, or may be performed ThreadPoolExecutor ScheduledThreadPoolExecutor. The difference between them is Runnable not return results, but Callable can return a result. Executors factory class may be used to put a package into a Runnable interface Callable.
ststic a Callable public <Object> Callable (the Runnable Task);
public ststic <T> a Callable <T> Callable (the Runnable Task, Result T);

 

Guess you like

Origin www.cnblogs.com/lym414/p/11234052.html