Java multithreading notes

Source: Internet
Author: User

Java multithreading notes
1. Use the new Thread (runnableObj) method instead of inheriting from the Thread.
For time-consuming tasks, put them in the thread for execution
Call the new Thread (runnable). start () method to start the Thread. The corresponding runnalbe. run method will be called in the Thread.
2. Thread interruption Method: Call the interrupt method to set the thread interruption status. Check the interrupt bit to determine whether the Thread is interrupted: Thread. currentThread (). isInterrupted ().
CurrentThread can be used to obtain the current thread.
The sleep method clears the interrupt status and throws InterruptedException.
Interrupt () sends an interrupt request to the thread and sets the interrupt status to true.
The interrupted () method checks whether the thread is interrupted. If yes, the interruption state is cleared.


Thread status: New, Runnable (the status after start is called, the status of the thread being executed, and the status of the thread waiting for execution are all runable), Blocked is Blocked, Waitting, Timed waiting, terminated.


Blocking: 1. Wait for the lock to be released; 2. When the thread waits for another thread to notify the scheduler of a condition, it enters the waiting state. The method has a timeout parameter, timeout will enter the timing wait status. Such as Thread. sleep, Object. wait (), Thread. join (), Lock. tryLock (), Condition. await ()


3. join () is waiting to terminate the specified thread, and join (long mills) is waiting for the specified thread to die or the specified number of milliseconds;
Thread. State getState () gets the Thread State
4. The thread inherits the priority of the parent thread. Use setProperty to adjust the priority. The value ranges from 0 ~ 10. The higher the value, the higher the priority.
Static void yield () This method causes the current execution thread to be in the concession State. If a thread with the same priority exists, it will be executed first.
5. this. setDaemon (true) converts a thread to a daemon. this method must be called before the thread starts. The purpose of a daemon thread is to provide services for other threads. When only the daemon thread is left, the VM exits. The daemon thread should never access fixed resources, such as files and databases, because it may be interrupted during an execution process at any time.
6. run Of a thread cannot throw an exception to be detected. Undetected exceptions may cause thread termination. Exceptions before thread death will be passed to a processor for uncaptured exceptions. This processor implements the Thread. UncaughtExcetptionHandler interface. If the default processor is not installed, the default processor is null. If a processor is not installed for an independent thread, the processor is a ThreadGroup object.
Do not handle exceptions that can be passed in Catch statements.


Javap-c-v Bank is used to decompile Bank. class.


7. Use synchronized to ensure concurrent access to code blocks.
ReentrantLock is a lock object that can be used to control concurrency. Declare a lock object in a public access code. Obtain the lock before try, and release the lock in finally. Instead of using the lock object as a thread member.
The lock can be reentrant, And the thread can repeatedly obtain the held lock. The lock holds a counter. When other methods are called in the critical section, the count is incremented by 1. When the called method exits, the lock is reduced by 1.
Handle exceptions in the critical section. Do not jump out of the critical section due to exceptions.
8. The condition object is used by the thread to perform operations when a condition is met. Simple locks cannot meet this scenario.
A lock can be associated with multiple Condition variables. BankLock. newCondition () creates the condition variable associated with the lock. In the critical section, while (condition no statisfy) condition. await (); is required to be called in the loop body. By calling the await method in the condition variable, it will enter the waiting set of the condition and block it. Waiting for another thread to call the signalAll method on the same condition (the blocking of all threads waiting for this condition will be lifted, so that the thread to be removed can access the object through competition after the current thread exits ). The signal () method is to randomly remove a blocked thread. This method must ensure that the thread to be removed can be executed; otherwise, a deadlock may occur.
Each condition object manages the threads that have entered the protected code segment but cannot run.


Each object has a lock. To call the object member method declared by synchronized, you must obtain the internal object lock in advance.
The internal object lock has only one correlated condition object. wait will add the thread to the waiting set, and Y/policyall will remove the blocking status of the waiting thread. You can only use the wait and notify methods within synchronized to implement the conditional object waiting for a certain condition. The mode is similar to await and signal.
Generally, synchronized and Condition are not recommended, and synchronized is preferred.


Threads have local caches and registers, and can store values in memory temporarily. If a lock is used to execute concurrent access to shared variables, the compiler is required to refresh the local cache when necessary (update the value of shared variables locally) to maintain the lock effect.
Volatile provides a lock-free mechanism for Synchronous access, but it does not guarantee atomicity. If the shared variable does not complete other operations except the value assignment, you can declare it as volatile.
Atomic objects can add or subtract variables in an atomic manner.


9. public static final ThreadLocal DataFormat =
New ThreadLocal (){
Protect SimpleDateFormat initialValue (){
Return new SimpleDateFormat (yyyy-MM-dd );
}
}


10. lock timeout: if (myLock. tryLock (100, TimeUnit. MILLISECONDS) {...} throws InterruptedException upon timeout, which can be used to break the deadlock.
MyCondition. await (100, TimeUnit. MILLISECONDS)


11. Multiple read threads use less ReentrantReadWriteLock.
Private rwLock = new ReentrantReadWriteLock ();
RLock = rwLock. readLock (); it is shared by all read threads and will reject the use of rLock. lock () before the write operation is read; Use rLock. unlock () after the end ();
WLock = rwLock. writeLock (); reject other read and write operations n. Use wLock. lock () before writing; Use wLock. unlock () after writing ();


12. Blocking queue BlockingQueue (which has several inheritance classes: BlockingQueue, blockingdeque, and ArrayBlockingQueue) is a queue used to store shared data in the producer and consumer model. This queue considers concurrent operations between producers and consumers to balance the load of producer and consumer speed. Use offer to add an element, poll to remove and return the element, and peek to return the element (these three operations can specify the operation timeout ).
PriorityBlockingQueue is the priority queue.


13. thread security set: congestion queue, ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentSkipListSet (these two are thread-safe ordered sets that require the Comparable interface in advance), concurrent1_queue. the size () of these sets needs to be determined through traversal, which is different from the general set.
These sets return weak consistency iterators, which may not necessarily return the modified value, but will not return the same value twice, and will not throw ConcurrentModificationException.
ConcurrentHashMap (Int initialCapacity, float loadFactor, int concurrentLevel); the parameter is the initial capacity of the specified set. The default value is 16. concurrentLevel is the estimated number of concurrent writer threads. It indicates that up to 16 Write processes can write at the same time. If more than 16 Write processes are used, the remaining threads will be blocked.
ConcurrentHashMap. putIfAbsent (k, v) inserts a kv pair when the key does not exist. Otherwise, the value corresponding to the Return key k is used.




Copy the written array:
CopyOnWriteArrayList and CopyOnWriteArraySet. The write thread modifies the underlying data. If the number of read threads is greater than the number of write threads, this type of set is suitable. Read/write consistency can be maintained without synchronization.


Any collection class can be changed to thread-safe by means of synchronous wrapper. It is implemented by adding a lock to the collection. This is not recommended because synchronized (synchashMap) needs to be added to the accessed code) {...}, we recommend that you use the ConcurrentXXX set:
List SyncArrayList = Collections. synchronizedList (new ArrayList ());
HashMap SyncHashMap = Collections. synchronizedMap (new HashMap ());
For the list of frequently modified arrays, using synchronized (arrayList) {} has better performance than CopyOnWriteArrayList.




14. Call back Callable and Future. Runnalbe is an Asynchronous Method without return values or parameters. Callable and Future return values. Callable {E call ();} only one method returns call () of the type E ().
Future saves the asynchronous calculation result. Its get (long timeout, TimeUnit) can specify the timeout time and interrupt the timeout time. If Future is still being executed, isDone () returns false. The cancle () method cancels this operation.


The FutureTask package can convert Callable to Future and Runnable.
Callable MyCompution = ..;
FutureTask Task = new FutureTask (MyCompution); // construct an object that is both Future and Runnable.
Thread t = new Thread (task );
T. start ();
...
Integer result = task. get (); // calls to get will be blocked until there are available results or timeout.


15. Executor
If the program contains a large number of threads with short lifecycles, it is best to use the thread pool. The thread pool contains many Idle threads to be run. When Runnable is handed over to the thread pool, a thread will call Runnable. run (). When the run exits, the thread returns to the thread pool and waits for the next operation.
The thread pool can reduce the number of concurrent threads.
There are many static methods in Executor that can be used to build a thread pool: newCachedThreadPool Idle threads are saved for 60 s; newFixedThreadPool fixed number of threads and Idle threads are kept all the time. If the number of tasks is greater than the number of threads, unexecuted tasks are placed in the queue waiting for available Idle threads. The newSingleThreadPool has only one thread for sequential execution. These methods return ThreadPoolExecutor objects that implement the ExecutorService interface.
Use the Future in the ExecutorService Interface Submit (Runnable, T result); Future Submit (Callable Task) method to submit Runnable and Callable objects to ExecutorService.
Call shutdown () to close the thread pool after the thread pool is used up.


Steps:
A. Executors. newFixedThreadPool ()
B. submit submits Runnable or Callable objects;
C. Obtain the result of the Future object and call result. get ();
D. Shut down the thread pool ()




15. scheduled execution (scheduled task)
The ScheduledExecutorService interface is designed for scheduled or repeated tasks.
ScheduledExecutorService ss = Executors. newScheduledThreadPool ();
Schedule (Callable/Runnable, initDelayTime, TimeUnit );
ScheduleAtFixedRate (Callable/Runnable, initDelayTime, long period, TimeUnit); // execute once every period


16. Control the Task Group
Executor can be used to control a group of related tasks.
InvokeAny: execute multiple tasks. Once one execution is complete, it can be completed.
InvokeAll: multiple tasks are executed, and all tasks can be completed after being executed. The usage is as follows:
List > Tasks = ...;
List > Results = executor. invokeAll (tasks );
For (Future Res: results) {// sequential traversal takes a lot of time to wait when the first task takes a long time. We recommend that you use ExecutorCompletionService to save the result in the order of result generation, which is more effective.
ProcessFuturer (result. get ());
}


17. fork-join framework (large tasks are divided into small tasks and merge is executed in parallel)
RecursiveTask is used to return computing results, while RecursiveAction is used to return non-computing results. The compute between the two is used to generate and call subtasks and merge the results.
Class Counter extends RecursiveTask {// Grouping Algorithm
Protect Integer compute (){
If (to-from Else {
Int mid = (low + high)> 1;
Counter first = new Counter (from, mid); // split a molecular task
Counter second = new Counter (mid + 1, high );
InvokeAll (first, second); // scheduling all subtasks
Return first. join () + second. join (); // merge the result.
}
}
}
Main (){
ForkJoinPool pool = new ForkJoinPool ();
Pool. invoke (counter );
System. out. println (counter. join ());
}


18. synx
Provides classes for mutual cooperation between threads:
CyclicBarrier: waits for a certain number of threads to reach a public barrier and executes a processing barrier action.


CyclicBarrier barrier = new CyclicBarrier (numThreads, barrierAction); // when numThreads reach the barrierAction
Runnable {
Public void run (){
DoSomething...
Barrier. await (); // wait until the barrier is opened. You can set a timeout value. If an exception is thrown during the timeout period, other threads waiting for await will throw a BrokenBarrierException.
...
}
}


CountDownLatch: Allows waiting until the counter is 0. Used when one or more threads need to wait until a specified number of events occur. This is one-time and only available once.
Exchanger: allows two threads to swap objects when they are ready. Two threads are on two different instances of the same data structure. One is used to add data to the instance, and the other is used to clear data.
Semaphore: allows threads to wait until execution is allowed. Restrict the number of threads used to access resources.
Semaphores manage many permits to limit the number of threads passed. Semaphores maintain only one count. Other threads call release () to release the license permits.


SynchronousQueue: allows one thread to deliver an object to another thread. When no explicit synchronization is performed, two threads upload an object from one thread to another.

 

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.