Java Multi-Threading and Concurrent Learning summary analysis _java

Source: Internet
Author: User

1. Computer system
Use caching as a buffer between memory and processor, copying the data needed for the operation to the cache, allowing for rapid computation, and synchronizing back into memory from the cache when the operation is finished, so that the processor does not have to wait for slow memory reading and writing.

Cache consistency: In multiprocessor systems, some protocols are required to synchronize back to main memory, because sharing the same main memory, when multiple processor operations are designed to the same memory area, may result in inconsistencies in their cached data.

Perform optimizations in order to make the unit within the processor as fully leveraged as possible.

2.JAVA memory model
The goal is to define access rules for each variable in the program. (includes instance fields, static fields, and elements that make up an array, excluding local and method parameters)

1. All variables are stored in main memory (part of the virtual machine memory).
2. Each thread is made up of its own working memory, in which the thread's working memory holds the primary memory copy of the variable used by the thread, and all operations of the thread on the variable must be performed in working memory and not directly read or written to the variables in the main memory.
3. There is no direct access to the other's working memory variables between threads, and the transfer of variables between threads needs to be done through main memory.

Inter-memory interoperation:

Lock (Lock): A variable that acts on the main memory and identifies a variable as a thread-exclusive state.

Read (read): A variable that acts on the main memory, transferring the value of a variable from main memory to the working memory of the thread.

Load (load): A variable that acts on the working memory, putting the value of a variable from the main memory into a variable copy of the working memory.

Use: A variable acting on working memory that passes the value of a variable in working memory to the execution engine.

Assign (Assignment): A variable that acts on the working memory, assigning a value received from the execution engine to a variable in working memory.

Store: A variable in working memory that transmits the value of a variable in working memory to the main memory.

Write (write): A variable that acts on the main memory, putting the value of a variable in the store operation from working memory into a variable in the main memory.

Unlock (unlock): A variable that acts on the main memory, releasing a variable in a locked state, which can then be locked by another thread.

Rules:

1. Do not allow one of the read and load, store, and write operations to appear alone.

2. A thread is not allowed to discard the most recent assign operation, and the variable must be synchronized back into main memory after it has changed in working memory.

3. Does not allow a thread to not have any assign operation to synchronize data from the thread's working memory back into the main memory.

4. A new variable can only be born in main memory.

5. A variable at the same time allows only one thread to lock it, but can be repeatedly executed by the same thread.

6. If you perform a lock operation on a variable, the value of this variable in working memory is emptied and the read, load operation needs to be rerun before the execution engine uses the variable.

7. If a variable is not locked beforehand by the lock operation, it is not allowed to perform a unlock operation.

8. Before performing a unlock operation on a variable, you must first synchronize the variable back into the main memory.

Type 3.volatile variable
1. Ensure the visibility of this variable to all threads. Each thread needs to be refreshed before using this type of variable, and the execution engine cannot see the inconsistency.
The results of the operation do not depend on the current value of the variable, or ensure that only a single thread modifies the value of the variable.

Variables do not need to participate in invariant constraints with other state variables.

1. Disable command reordering optimization. Ordinary variables ensure that the correct results are obtained in all the places that rely on the result of the assignment during the execution of the method. It is not guaranteed that the order of assignment operations is consistent with the order in the program code.
2.load must be present at the same time as use; Assign and store must appear simultaneously.

4. Atomicity, Visibility and order
Atomicity: Access to read and write for basic data types is atomic, and the operation between synchronized blocks is also atomic in nature.

Visibility: means that when a thread modifies the value of a shared variable, other threads can immediately learn about the change. Synchronized (rule 8) and final can guarantee visibility. When a final-decorated field is initialized in the constructor, and the constructor does not pass a reference to this, the value of the final field is visible in other threads.

Ordering: The volatile itself contains the semantics of prohibiting order reordering, whereas synchronized is obtained by rule 5, which determines that two synchronized blocks holding the same one can only be entered serially.

5. Principle of prior occurrence
The partial order relationship between two operations defined in the Java memory model, if operation a precedes operation B, it means that the effect of operation A can be observed by Operation B before the action B occurs.

Program Order rules: In a thread, in the code control flow order, in the previous operation first occurred in the following operation.

Thread locking rule: A unlock operation first occurs after the lock operation facing the same lock.

Volatile variable rule: a write operation on a volatile variable first occurs after the read operation of the variable is encountered.

Thread Start rule: the Start () method of the Thread object occurs first in each operation of this thread.

Thread termination rule: All operations in a thread occur prior to the termination detection of this thread.

Thread break rule: a call to a thread's interrupt () method takes place first in the Code detection interrupt event of the interrupted thread.

Object is terminated: Initialization of an object occurs first in its finalize () method.

Transitivity: If operation a first occurs in Operation B, and Operation B occurs in Operation C, then it is possible to conclude that operation a first occurs in Operation C.

There is basically no relationship between the order of time and the principle of prior occurrence.

6. Thread implementation
Using kernel thread implementations:

Kernel thread kernel Thread: threads that are directly supported by the operating system kernel, where the kernel class completes the thread switch, and the kernel schedules the threads by manipulating the scheduler and is responsible for mapping the tasks of the threads to the individual processors.

Lightweight processes Light Weight processes: Each lightweight process is supported by a kernel thread.

Limitations: All process operations require system calls (system calls are relatively expensive and need to be switched back and forth in user and kernel states); Lightweight processes consume a certain amount of kernel resources, and the number of systems that support lightweight processes at one time is limited.

Using the user thread implementation:
User thread: It is completely built on the line threading of user space, the system kernel can't perceive the realization of thread existence directly. The creation, synchronization, destruction, and scheduling of user threads are complete in the user state and do not require the help of the kernel. All thread operations require the user to process themselves.

Mixed implementations:
The way in which the kernel thread and the user thread are used. The lightweight process supported by the operating system serves as a bridge between the user thread and the kernel thread.

The Sun JDK, whose Windows and Linux editions are implemented using a one-to-one threading model, maps a Java thread to a lightweight process.

7. Thread Scheduling
Thread scheduling refers to the process by which the system assigns the processor to the thread: cooperative, preemptive.

Synergy: The execution time of a thread is controlled by the thread itself, and after the thread has done its work, it actively notifies the system to switch to another thread. Disadvantage: Thread execution time is not controllable.

Preemption: Each thread will be allocated execution time by the system, and the thread's switching is not determined by the thread itself. Java uses this method of invocation.

Thread priority: On some platforms (operating system thread priority is less than Java thread priority) the different priorities actually become the same, and the priority may be changed by the system itself.

8. Thread state
Thread State:
Create New:
Run Runnable:

Wait indefinitely for waiting: Wait for other lines to wake up Cheng.

Object.wait () is not set for the timeout parameter, thread.wait () is not set for the timeout parameter.

Deadline waiting timed_waiting: The system wakes up automatically after a certain time.

Sets the object.wait () of the timeout parameter, sets the Thread.wait () of the timeout parameter, and the Thread.Sleep () method.

Blocking blocked: Waiting to get a exclusive lock, waiting to enter a sync area.

End Terminated:

9. Thread Safety
Thread safety: When multiple threads access an object, the This object is thread-safe if you do not have to consider the scheduling and swapping execution of these threads in the run-time environment, or the need for additional synchronization, or any other coordinated action by the caller that invokes the object's behavior to get the correct result.

Immutable: As long as a immutable object is correctly constructed. The base data type decorated with the final keyword; if the shared data is an object, it is necessary to ensure that the behavior of the object does not have any effect on its state (the object of the String class). Method: Declare a variable with state in the object as final, such as the Integer class. IS: enumeration type, part of number subclasses (except Atomicinteger and Atomiclong).

Absolute thread Safety:
Relative thread safety: Separate operations on this object are thread-safe. Thread safety in the general sense.

Thread-compatible: it is necessary to use synchronization to ensure that objects are used securely in the concurrency environment by means of the caller.

Thread antagonism: Code that cannot be used concurrently in a multithreaded environment, regardless of whether the caller has taken synchronization measures. There are: System.setin (), System.setout (), System.runfinalizersonexit ()

10. How to implement thread safety
1.1. Mutex synchronization: Synchronization is the guarantee that shared data is used by only one thread at a time when multiple threads concurrently access shared data. Mutual exclusion: Critical area, mutex, and semaphore.

Synchronized keyword: After compiling, the Monitorenter and monitorexit two byte code instructions are formed before and after the synchronized block respectively. All two directives require a reference type parameter to indicate the object to lock and unlock. If you do not explicitly specify an object parameter, the object instance or class object will be used as the lock object, depending on whether the synchronized is decorated with an instance method or a classes method.

In the execution of the monitorenter instruction, first try to get the object's lock, if not locked or when the line already has the lock of the object, then the lock counter plus 1, the corresponding execution moniterexit, the lock counter 1, when the counter is 0 o'clock, the lock was released. If getting an object lock fails, the current thread will block the wait.

Reentrantlock advanced features relative to synchronized:

Wait interruptible: When the thread holding the lock does not release the lock for a long time, the waiting thread can choose to discard the wait and handle other things instead.

Fair locks: When multiple threads are waiting for the same lock, they must acquire the lock one at a time according to the sequence of events in which the lock is requested, and when the unjust lock is freed, any thread that waits for the lock has the opportunity to acquire the lock. The lock in the synchronized is a fair lock, and Reentrantlock is not a fair lock by default.

Lock binding multiple conditions: A Reentrantlock object can bind multiple condition objects at the same time.

1.2. Non-blocking synchronization:
Optimistic concurrency strategy based on conflict detection: First, if no other thread is competing for shared data, then the operation succeeds; if the shared data is contention and conflicts arise, then other compensation measures (typically a continuous attempt until successful) are made.

Atomicinteger and other atomic classes provide a way to implement CAS directives.

1.3. No sync scheme:
Reentrant code: You can break it at any time the code executes, instead of executing another piece of code, and the original program does not have any errors after the control returns. Features: Do not rely on the data stored on the heap and public system resources, the amount of state used is passed by the parameters, do not call the method of not reentrant. If a method, its return results can be predicted, as long as the same data to return to the same results, it will meet the requirements of reentrant.

Thread-Local Storage: If the data needed in a piece of code must be shared with other code, see if the code for the shared data is guaranteed to execute on the same thread.

A.threadlocal class
ThreadLocal: A thread-level local variable that provides a separate copy of the variable for each thread that uses the variable, and each thread modifies the replica without affecting a copy of the other thread object. Threadlocal instances typically appear in a class as static private fields.

11. Lock Optimization
1.1. Spin Lock
In order for the thread to wait, let the thread perform a busy loop (spin). Requires a physical machine to have more than one processor. While the spin wait avoids the overhead of threading, it takes up processor time, so if the lock is taken for a short time, the spin wait will be very good, whereas the spin thread will only consume the processor resources in vain. The default value for the spin number is 10 times, and you can change it using the parameter-xx:preblockspin.

Self-adaptive spin Lock: Spin time is no longer fixed, but by the previous time in the same lock and the state of the owner of the lock to decide.

1.2. Lock Removal
When the virtual machine Just-in-time compiler is running, for some code requirements synchronization, but is detected that there is no possibility of the existence of shared data competition for the lock to clean up (escape analysis technology: All the data on the heap will not escape from the other threads to access, you can treat them as data on the stack).

1.3. Lock coarsening
If a virtual machine detects that a string of fragmented operations locks up the same object, it extends the scope of the lock synchronization to the outside of the entire sequence of operations.

Hotspot the memory layout of the object of the virtual machine: is the header (object header) divided into two parts, the first part (Mark Word) is used to store the Run-time data of the object itself, and the other is used to store pointers to the data types of the method area object, if it is an array, An extra portion is also used to store the length of the array.

When an object is not locked in a 32-bit hotspot virtual machine, Mark Word's 25 bits in 32 bits space are used to store the object hash code, 4-bit storage objects are generational, 2-bit storage-lock flag bits, and 1-bit fixed to 0.

Hotspot Virtual Machine Object Header Mark Word

Storing content

Sign bit

State

Object hash code, object generational age

01

Not locked

Pointer to lock record

00

Lightweight lock

A pointer to a heavy lock

10

Expansion (heavy-level lock)

Empty, no information logged

11

GC Tags

Biased thread ID, bias time stamp, object generational age

01

can be biased


1.4. Lightweight lock
When the code enters the synchronization block, if the synchronization object is not locked, the virtual machine first creates a space in the current thread's stack frame, called the lock record, to store the copy of the object's current mark Word. The virtual machine then uses the CAS action to try to update the object's mark Word to a pointer to execute the lock record. If successful, the thread has a lock on the object. If the update operation fails, the virtual machine first checks whether the object's mark word points to the current thread's stack frame and, if so, indicates that the current thread already has the lock on the object, otherwise the object has been preempted by another thread. If more than two threads compete with the same lock, the lightweight lock is no longer valid and expands to a heavyweight lock.

Unlock process: If the object's Mark Word still points to the thread's lock record, replace the object's current mark Word with the displaced mark word that is copied in the thread with the CAS operation and complete the process if the replacement succeeds. If a failure indicates that another thread has tried to acquire the lock, it is necessary to wake the suspended thread while releasing the lock.

The basis of lightweight locks: For most locks, there is no competition throughout the synchronization cycle.

Traditional locks (heavy-level locks) are implemented using operating system mutexes.

1.5. Bias Lock
The aim is to eliminate the synchronization primitives in the absence of competition, and further improve the performance of the program. The lock favors the first thread that obtains it, and if the lock is not acquired by another thread during the subsequent execution, the thread holding the lock will never need to synchronize again.

When the lock is first acquired by a thread, the virtual machine will set the flag bit in the object header to 01, while using CAs to record the ID of the thread that acquired the lock in the object's Mark Word, and if it succeeds, each time the thread that holds the lock in the lock will enter the synchronization block associated with it, can be done without any synchronization operation.

When another thread attempts to acquire the lock, the bias pattern ends. Revert to an unlocked or lightweight lock state, depending on whether the object is currently locked or not.

12. Kernel State and User state
The operating system has two operational levels, and Intel CPUs provide-ring3 three operating modes.

RING0 are left to operating system code, device driver code, which works in a system-core mindset, while Ring3 is used by ordinary user programs that work in user state. Code running in the processor kernel mindset is free of any restrictions and can access any valid address directly. Code running in user state is subject to a number of checks by the processor, and they can only access the virtual address of the page in user state as specified in the page table entries that map their address space, and only the I/O permission bitmap (I/O Permission in the Task State segment (TSS)) BITMAP) for direct access to the accessible ports specified in the.

13. Common methods
1.1.object.wait ():
The current thread T waits (thread T must have a lock on the object) before another thread calls the Notify () or Notifyall () method of the object, or exceeds the specified amount of time. The thread t is placed in the rest area of the object and the lock is released. The thread t is removed from the object's rest area and the thread is again dispatched, in the event of a wake-up, interrupt, timeout. Once the thread T obtains the lock on the object, all the synchronization declarations on the object are restored to the state when the wait () method is invoked, and then the thread T is returned from the Wait () method. Interruptedexception is thrown if the current thread is interrupted by any thread before or while waiting. This exception is thrown when the lock state of this object is restored as described above. The interrupt state of the current thread is cleared when this exception is thrown.

Only the lock of this object is freed and does not release other synchronization resources held by the current thread.

1.2. Object.notify ()
Wakes a single thread waiting on this object lock. This method can only be invoked by threads that own the lock of the object.

1.3. Thread.Sleep ()
Lets the currently executing thread hibernate (suspend execution) within the specified number of milliseconds, which is affected by the system timer and scheduler precision and accuracy. The monitoring status is still maintained, automatically restored to the operational state, and no object locks are released. If any thread interrupts the current thread. The interrupt state of the current thread is cleared when the interruptedexception exception is thrown. Give up the execution time for the CPU allocations.

Thread.Join (): Called on a Thread object so that the current thread waits for the thread that corresponds to the thread to end.

Thread.yield (): Pauses the currently executing thread object and executes other threads.

Thread.Interrupt ()
Break the thread, stop everything it's doing. Interrupting a thread that is not active has no effect.

If a thread is blocked during the call to the Wait () method of the object class, or the join (), sleep () method, its break state is cleared and a interruptedexception is received.

Thread.interrupted (): detects if the current thread has been interrupted and clears the interrupt state of the thread (back to non-disruptive state).

Thread.isalive (): Active if the thread is already started and has not been terminated.

Thread.setdaemon (): needed to be called before the start () method call. When a running thread is a background thread, the Java virtual machine exits. Otherwise, when the main thread exits, the other threads will still continue to execute.

14. Other
1. When you invoke Wait (), notify (), Notifyall () of object, a Illegalmonitorstateexception exception is thrown if the current thread does not get the object lock.

1. If a method is declared synchronized, it is equivalent to calling synchronized (this) on this method.
If a static method is declared as synchronized, it is equivalent to calling synchronized (class. Classes) on this method. When a thread enters a synchronous static method, other threads cannot enter any of the static synchronization methods for this class.

1. The line Cheng is the owner of the object lock:
1. By executing the Synchronized instance method of this object
2. The body of the synchronized statement that synchronizes on this object
3. For objects of class type, you can perform a synchronous static method of the class.

1. Deadlock:
A deadlock is two or more threads that are blocked indefinitely, and the threads wait for resources to each other.

May occur in the following situations:
When two threads call each other thread.join ();
When two threads use a nested synchronization block, one thread takes up the lock that another thread must have, and a deadlock can occur when the other is blocked while waiting.

1. The start () method of the thread class is invoked (requesting another thread space from the CPU to execute the code in the Run () method), and the Threads ' run () method does not necessarily execute immediately, but rather waits for the JVM to dispatch.
The run () method contains the body of the thread, which is the code that will run after the thread is started.

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.