Java concurrent Programming--a summary after reading

Source: Internet
Author: User
Tags closure volatile

1. Introduction

1.1 History of concurrency

Cause: Resource utilization, fairness, convenience

1.2 Advantages of threading

1.2.1 Powerful multi-processor capabilities

The simplicity of 1.2.2 Modeling

Simplified processing of 1.2.3 asynchronous events

1.2.4 responds to a more responsive user interface

1.3 Threads Bring the popularity

1.3.1 Security Issues

There's never going to be a bad thing

1.3.2 Active Issues

Something right will eventually happen.

1.3.3 Performance Issues

Hope the right thing happens as soon as possible

1.4 Threads everywhere

The framework you are using may create threads

Timer class, used to defer running a task one or more times to ensure that the Access object is thread-safe

Servlets and JSPs need to ensure thread safety for multiple servlet shared objects

Remote Method invocation

Swing and AWT

2. Thread Safety

2.1 What is thread safety

This class always shows the correct behavior when multiple threads access a class, which is thread-safe

Stateless objects must be thread-safe

2.2 atomicity

2.2.1 Race condition

When the correctness of the calculation depends on the timing of the execution of the thread, the condition will occur.

The condition conditions of judging based on the observation result of failure are called "first check and then execute"

2.2.2 Example: Race condition in deferred initialization

2.2.3 Compound operation

Operations such as "first check after execution" and "read-Modify-write" are collectively referred to as composite operations

2.3 Plus lock mechanism

2.3.1 Built-in lock

2.3.2 Re-entry

2.4 Using locks to protect status

2.5 Activity and performance

Do not hold locks when performing long calculations or operations that may not be completed quickly

3. Sharing of objects

3.1 Visibility

3.1.1 Failure data

Gets the value to an update that is not updated

3.1.2 64-bit operation for non-atomic

The resulting failure data is the lowest security, not the random value, but not for a non-volaties type of 64-bit numeric variable, because the JVM decomposes 64-bit read and write operations into 2 32-bit operations

It is not safe to use variables of a shared and variable type such as long and double in multi-threading, unless protected with volatie declarations or locks

3.1.3 Locking and visibility

3.1.4Volatile variables

Volatile variables are shared, and read volatile variables always get the latest values

However, volatile variables are fragile and should only be used if volatile variables can simplify code invalidation and validate synchronization policies.

The locking mechanism ensures visibility and atomicity, and volatile variables only ensure visibility

3.2 Release and escape

Publish: Enables an object to be used in code outside the current scope

Escape: An object that should not be published is called an escape when it is published

Secure object Construction Process

Do not use this escape in the construction process

Use the factory to place this reference in the construction process escaping

3.3 Thread closure

3.3.1ad-hoc Thread Closure

The responsibility for maintaining thread closeness is fully implemented by the program, but it is fragile and minimizes

3.3.2 Stack Closure

3.3.3ThreadLocal class

Associates a value in a thread with the object that holds the value, always getting the latest value

Threadlocal variables are similar to global variables, reducing the reusability of code and introducing implicit coupling between classes

3.4 invariance

3.4.1Final Domain

3.4.2 Example: Using volatile types to publish immutable objects

3.5 Security release

3.5.1 Incorrect publication: The correct object is destroyed

3.5.2 non-oral object with initialization security

Common patterns for 3.5.3 security releases

Initializing an object reference in a static initialization function

Save the object's reference to a volatile type of field or Atomicreferance object

Saves a reference to an object in the final type field of a properly constructed object

Save a reference to an object in a lock-protected domain

3.5.4 Facts Non-mutable objects

Objects are technically mutable, but objects whose state is not changed after publication are called "Fact immutable objects".

3.5.5 mutable objects

Immutable objects can be published arbitrarily

Fact immutable objects are published in a secure manner

Mutable objects are published in a secure manner and must be thread-safe or lock-protected.

3.5.6 a secure shared object

Policies: Thread blocking, read-only sharing, thread-safe sharing, protecting objects

4. Combination of objects

4.1 Designing Thread-safe classes

4.1.1 Collecting synchronization requirements

4.1.2 Dependent State operation

Ownership of the 4.1.3 State

4.2 Instance Closure

4.2.1Java Monitor Mode

4.2.2 Example: Vehicle tracking

4.3 Thread-Safe delegation

4.3.1 Example: Consignment-based vehicle tracker

4.3.2 Independent State variables

4.3.3 when a delegate fails

4.3.4 Publishing the underlying state variable

4.3.5 Example: Vehicle tracker for release status

4.4 Adding functionality to existing thread-safe classes

4.4.1 Client lock mechanism

For client-side code that uses an object x, protect this client code with the lock that the x itself uses to protect its state

If not, the correct helper class is added

 Public classListhelper<e> {     Publiclist<e> list = Collections.synchronizedlist (NewArraylist<>());  Public Booleanputifabsent (E x) {synchronized(list) {//Notice the Locked object            BooleanAbsent =!list.contains (x); if(absent) {List.add (x); }            returnabsent; }    }}

Can disrupt the encapsulation of synchronization policies

4.4.2 Combination

 Public classImprovedlist<t>ImplementsList<t> {    Private FinalList<t>list;  PublicImprovedlist (list<t>list) {         This. List =list; }     Public synchronized Booleanputifabsent (T x) {Booleancontains =list.contains (x); if(contains) {List.add (x); }        return!contains; }}

4.5 Document the synchronization policy

Explain vague documents

5. Basic building Blocks

5.1 Synchronizing Container classes

5.1.1 problems with the synchronization container class

5.1.2 Iterators and Concurrent-modificationexception

5.1.3 Hidden iterators

5.2 Concurrent Containers

5.2.1ConcurrentHashMap

5.2.2 Additional atomic map operations

5.2.3CopyOnWriteArrayList

The copy on write container should be used when there are far more iterations than the modify operation

5.3 Blocking queues and producer-consumption patterns

5.3.1 Example: Desktop Search

5.3.2 Serial Thread closure

5.3.3 double-ended queue and working secret

5.4 Blocking method and interrupt method

Recovery interrupt

5.5 Synchronization Tool Class

5.5.1 Latching

Delays the progress of a thread until it reaches the terminating state, and is used to ensure that certain activities are not executed until other activities are completed

 Public classtestharness { Public LongTimetasks (intNthrads,FinalRunnable Task)throwsinterruptedexception {FinalCountdownlatch startgate =NewCountdownlatch (1);//Start Door        FinalCountdownlatch endgate =NewCountdownlatch (nthrads);//End Door         for(inti = 0; i < nthrads; i++) {Thread T=NewThread () { Public voidrun () {Try{startgate.await ();//wait for all threads to be ready                        Try{task.run (); } finally{endgate.countdown ();//minus 1 to finish one thing .                        }                    } Catch(Interruptedexception ignored) {}}};        T.start (); }        LongStart =System.nanotime ();        Startgate.countdown ();        Endgate.await (); LongEnd =System.nanotime (); returnEnd-start; }}

5.5.2FutureTask

For latching

5.5.3 Signal Volume

Count semaphores are used to control the number of simultaneous accesses to a specific resource

5.5.4 Fence

All threads must reach the fence at the same time to continue execution, and the fence can be reset for reuse

5.6 Building an efficient and scalable result cache

6. Task execution

6.1 Performing tasks in threads

6.1.1 performing tasks in a serial manner

6.1.2 Create a thread for a task in the display

6.1.3 Unlimited creation of threads

The cost of the thread life cycle is very high

High resource consumption

Poor stability

6.2Executor Frame

6.2.1 Example: Executor-based Web server

 Public classTest {Private Static Final intNthreads = 100; Private Static FinalExecutor exec =Executors.newfixedthreadpool (nthreads);  Public Static voidMain (string[] args)throwsIOException {serversocket socket=NewServerSocket (8080);  while(true) {            FinalSocket connection =socket.accept (); Runnable Task=NewRunnable () { Public voidrun () {handlerequest (connection);            }            };        Exec.execute (Task); }    }}

6.2.2 Execution Policy

6.2.3 Thread Pool

Newfixedthreadpool () Creating a fixed-length thread pool

Newcachedthreadpool () creates a cacheable thread pool that, when the current scale exceeds the processing requirements, reclaims idle threads, adding new threads when demand increases, unlimited size

Newscheduledthreadpool () fixed thread pool that performs tasks in a deferred or timed manner

Life cycle of 6.2.4Executor

6.2.5 delay tasks and cycle tasks

The timer class has a problem with the accuracy, and the exception is canceled.

Newscheduledthreadpool is a task based on relative time that is used for interval execution, such as 1 minutes to check an activity

6.3 Finding the parallelism to use

6.3.1 Example: Serial page renderer

6.3.2 the task of carrying results callable and future

6.3.3 example using the future to implement the page renderer

The limitations of 6.3.4 in the parallelization of heterogeneous tasks

6.3.5completionservice:executor and Blockingqueue

6.3.6 Example: Implementing a page renderer with Completionservice

6.3.7 set a time limit for a task

6.3.8 Example: Travel booking Portal

InvokeAll () can add all future to the returned collection in the order of iterators in the task collection, and when all tasks are completed or interrupted or timed out, InvokeAll returns

7. Cancel and Close

7.1 Task Cancellation

7.1.1 Interrupt

User request Cancellation

A time-limited operation, a search task timed out, the task being searched is canceled

Application events, workarounds found, cancel tasks for other search solutions

Error

Shutdown, program or server shutdown

An interrupt request is made and the thread interrupts itself at the right moment

7.1.2 Interrupt Policy

7.1.3 Response Interrupt

7.1.4 Example: Timed Run

7.1.5 through the future to achieve cancellation

7.1.6 handling non-disruptive blocking

Synchronous socket I/O in the java.io package

java.io synchronous I/O in the package

asynchronous I/O for selector

Get a lock

7.1.7 has newtaskfor to encapsulate non-standard cancellation

7.2 Stopping a thread-based service

7.2.1 Example: Log service

7.2.2 Close Executorservice

7.2.3 "Poison Pill" object

When the queue gets this "poison pill" object, stop immediately

7.2.4 Example: A service that executes only once

    BooleanCheckmail (set<string> hosts,LongTimeout, timeunit unit)throwsinterruptedexception {executorservice exec=Executors.newcachedthreadpool (); FinalAtomicboolean Hasnewmail =NewAtomicboolean ((false)); Try {             for(FinalString host:hosts) {Exec.execute (NewRunnable () { Public voidrun () {if(Checkmail (host)) {Hasnewmail.set (true);            }                    }                }); }        } finally{exec.shutdown ();//secure shut-offexec.awaittermination (timeout, unit); }        returnHasnewmail.get (); }

Limitations of 7.2.5shuadownNow

7.3 Handling non-normal thread termination

Processing not captured once

7.4JVM off

7.4.1 Closing Hooks

Threads registered through Runtime.addshutdownhook, but not yet started

For cleaning up your service or application

7.4.2 Daemon Thread

All threads created by the main thread are normal threads

All threads other than the main thread creation are daemon threads

7.4.3 Terminator

8. Use of the thread pool

8.1 Coupling between tasks and execution processing

8.1.1 Thread Starvation Deadlock

A thread that waits for another thread to wait for a resource or condition to send a thread starvation deadlock

8.1.2 Long-running tasks

8.2 Setting the size of the thread pool

8.3 Configuring Threadpoolexecutor

Creation and destruction of 8.3.1 threads

8.3.2 Managing Queue Tasks

8.3.3 Saturation Strategy

"Abort" policy, discard the next task that will be executed

The "Caller runs" policy, which rolls back the task to the caller

8.3.4 Thread Factory

8.3.5 Custom Threadpoolexecutor after calling the constructor

8.4 Extension Threadpoolexecutor

Example: adding statistics to the thread pool

8.5 Parallelization of recursive algorithms

Example: Puzzle frame

9. Graphical User interface applications

9.1 Why the GUI is multithreaded

9.1.1 Serial Event Processing

Thread closure mechanism in 9.1.2Swing

9.2 Short-time GUI tasks

9.3 Long-time GUI tasks

9.3.1 Cancel

9.3.2 Progress identification and completion identification

9.3.3SwingWorker

9.4 Shared data Model

9.4.1 thread-Safe data model

9.4.2 Decomposition Data Model

9.5 Other forms of single-threaded subsystems

10. Avoid the danger of being active

10.1 Dead Lock

10.1.1 Lock Sequence Deadlock

10.1.2 Dynamic Lock Sequence deadlock

10.1.3 a deadlock that is sent between collaboration objects

10.1.4 Open Call

Calling a method without holding a lock is called an open call

10.1.5 Resource Deadlock

10.2 Avoidance and diagnosis of deadlocks

10.2.1 Support for timed locks

10.2.2 analysis of deadlocks through thread dump information

10.3 Other Active Dangers

10.3.1 Hunger

To avoid using thread precedence, you increase platform dependencies

10.3.2 Poor responsiveness

10.3.3 Live Lock

A live lock occurs when a number of mutually cooperative threads respond to each other and modify their state so that no one thread can continue execution.

By waiting for a random length of time and fallback can effectively avoid the occurrence of a live lock

11. Performance and Scalability

11.1. Thinking about Performance

11.1.1 Performance and Scalability

Operating Speed Indicator: Server time, wait time

Processing capacity Indicator: throughput

Scalability: The throughput or processing power of the program increases as you increase your computing resources

11.1.2 evaluation of various performance tradeoff factors

11.2Amdahl Law

11.2.1 Example: A serial part that is hidden in various frames

Application of 11.2.2Amdahl Law

Accurately estimate the proportion of the serial part during execution

11.3 Thread-introduced overhead

11.3.1 Context Switch

When the running thread is larger than the number of CPUs, the execution context of the currently running thread is saved, and the newly scheduled thread execution context is set to the current context

11.3.2 Memory Synchronization

11.3.3 Blocking

11.4 Reduction of the competition of the lock

11.4.1 narrowing the range of the lock (fast forward fast out)

11.4.2 reducing the granularity of locks

11.4.3 Lock Segment

11.4.4 Avoid hotspot domains

11.4.5 some alternatives to exclusive locks

11.4.6 Monitoring of CPU utilization

Not enough load

I/O intensive

External restrictions

Lock competition

11.4.7 say "No" to the object pool

11.5 Example: Comparing the performance of a map

11.6 Reducing the overhead of context switching

12. Testing of concurrent Programs

12.1 Correctness Test

12.1.1 Basic Unit Testing

12.1.2 testing for blocking operations

12.1.3 Security Testing

Testing of 12.1.4 Resource management

12.1.5 using callbacks

12.1.6 to generate more alternating operations

12.2 Performance Testing

12.2.1 added chronograph function in Puttaketest

12.2. Comparison of more than 2 kinds of algorithms

12.2.3 Responsiveness Measurement

12.3 Pitfalls of avoiding performance tests

12.3.1 Garbage Collection

12.3.2 Dynamic Compilation

12.3.3 false sampling of code paths

12.3.4 the level of non-true competition

12.3.5 Removal of useless code

12.4 Other test methods

12.4.1 Code Review

12.4.2 Static Analysis Tool

12.4.3 aspect-oriented testing technology

12.4.4 Analysis and monitoring tools

13. Display Lock

13.1Lock and Reentrantlock

13.1.1 polling lock and timing lock

13.1.2 an interruptible lock acquisition operation

13.1.3 locking of non-block structure

13.2 Performance Considerations

13.3 Fair Sex

13.4 promotion between synchronized and Reentrantlock

13.5 Read-write lock

14. Build a custom Sync tool

14.1 Management of State dependencies

14.1.1 Example: Passing a failure of a precondition to the caller

14.1.2 Example: Enable simple blocking with polling and hibernation

14.1.3 Conditional queue

14.2 Using conditional queues

14.2.1 Conditional predicates

14.2.2 Premature Awakening

14.2.3 Loss of Signal

14.2.4 Notice

14.2.5 Example: Valve class

Security issues for 14.2.6 subclasses

14.2.7 Package Condition Queue

14.2.8 Entry agreement and Export agreement

14.3 Display of Condition objects

14.4Synchronized Profiling

14.5AbstractQueuedSynchronizer

Aqs of the 14.6java.util.concurrent Synchronizer class

14.6.1ReentrantLock

14.6.2Semaphore and Countdownlatch

14.6.3FutureTask

14.6.4ReentrantReadWriteLock

15. Atomic variable and non-blocking synchronization mechanism

15.1 Disadvantages of the lock

15.2 hardware-to-concurrency support

15.2.1 Compare and Exchange

15.2.2 Non-blocking counters

15.2.3JVM support for CAs

15.3 Atomic Variable Class

The 15.3.1 atom variable is a better volatile

15.3.2 Performance Comparison: Locks and atomic variables

15.4 Non-blocking algorithm

15.4.1 non-blocking stacks

15.4.2 non-blocking linked list

Domain Updater for 15.4.3 atoms

15.4.4ABA problem

16.Java memory model

16.1 What is the memory model and why does it need it

Memory model of the 16.1.1 platform

16.1.2 reordering

Introduction to 16.1.3Java Memory models

16.1.4 with synchronization

16.2 Release

16.2.1 unsafe release

16.2.2 Security Release

16.2.3 Safe Initialization mode

16.2.4 double check plus lock

16.3 Security during initialization

Java concurrent Programming--a summary after reading

Related Article

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.