High concurrency programming for Java

Source: Internet
Author: User

First, the basic knowledge of multithreading

1.1 Introduction to processes and threads

When the program runs , it allocates its own independent run space in memory , which is the process

Thread : It is in the process and is responsible for a space in the current process that is eligible for independent running.

A process is responsible for the operation of the entire program, and the thread is the operation of a specific independent function in the program. a process , at least There should be a thread .

1.2 Introduction to Multi-threading

In a multi-tasking, multi-user system. There are many processes that occur every day.

Multithreading: In a process, we open multiple threads at the same time , allowing multiple threads to perform certain tasks at the same time ( function ).

( such as a backend service system, you can use multiple threads to respond to multiple client requests simultaneously )

The purpose of multithreading : to improve the efficiency of the program Operation .

Multi-Threading Principle:The CPU in the thread to do the time slice switch ( multi-threaded can improve the efficiency of the program, but not unlimited thread )

1.3 Two ways to implement threading

 1, the way to inherit the Thread

2, declare the way to implement Runnable interface

1.4 java Sync synchronized keywords

Plus synchronous Format:

Synchronized ( requires an arbitrary object (lock) ) {

code block to put operations on shared data}

Synchronized is a keyword in Java, which is a feature built into the Java language. If a block of code is modified by the synchronized , when a thread acquires the corresponding lock and executes the block, the other threads can only wait until the thread that acquires the lock releases the lock, which is There are only two cases in which a lock thread releases a lock :

1. the thread that gets the lock executes the code block, and then the thread releases the possession of the lock

2. The thread execution exception occurs when the JVM causes the thread to automatically release the lock.

so synchronized waits for the thread to wait indefinitely: this is a fatal disadvantage

So the lock was introduced to solve the problem.

1.5 Lock

The difference between 1.5.1 lock and synchronized

  1)Lock is not built into the Java language,synchronized is a Java language, so it is a built-in feature. Lock is a class that enables simultaneous access through this class;

2) Lock synchronized There's a very big difference synchronized No user is required to manually release locks when synchronized method or synchronized After the code block is executed, the system automatically frees the thread to occupy the lock, while the lock You must have the user manually release the lock , which can cause a deadlock if there is no active release lock.

options for lock and synchronized

  1)Lock is an interface, and synchronized is a keyword in Java, Synchronized is a built-in language implementation;

2) synchronized lock In the event of an exception, if you do not actively pass the unlock () to release the lock, it is likely to cause a deadlock phenomenon, so use the lock finally release lock in block;

  3)Lock allows the thread waiting for the lock to respond to interrupts, while synchronized does not, while using synchronized , the waiting thread waits until it is not able to respond to interrupts;

  4) lock can be used to know if there is a successful acquisition of locks, and synchronized is unable to do .

  5)Lock can improve the efficiency of multiple threads for read operations.

in terms of performance, if competitive resources are not intense, the performance of both is similar, and when competing resources are very intense (that is, there are a lot of threads competing at the same time), this time the performance of Lock is far superior to synchronized. Therefore, in the specific use, according to the appropriate circumstances to choose.

use of each method in the 1.5.2 Lock interface:

Lock (),trylock (),trylock (long time, timeunit unit), lockinterruptibly () is used to obtain a lock.

  The UnLock () method is used to release the lock.

1.5. The difference between the 34 methods of acquiring a lock:

  The lock () method is one of the most commonly used methods for acquiring locks. Waits if the lock has been fetched by another thread.

as mentioned earlier, if the use of Lockmust be actively released, and the lock will not be released automatically when an exception occurs. Therefore, in general, the use of lock must be in the try{}catch{} block , and the release of the lock is placed in the finally block in order to ensure that the lock must be released to prevent the occurrence of deadlocks.

The Trylock () method is a return value that represents the attempt to acquire a lock, returns trueif it succeeds,or returns if the fetch failed (that is, the lock was fetched by another thread) . False, it is said that this method will return immediately anyway. You won't be waiting there until you get the lock.

  The Trylock (long time, Timeunit unit) method and the trylock () method are similar, except that the method waits for a certain period when the lock is not taken. Returns False if the lock is not held within the time period . Returns trueif the lock was obtained at the beginning or if the lock was obtained during the wait period.

  The lockinterruptibly () method is special, and when the lock is acquired by this method, if the thread is waiting to acquire the lock, the thread can respond to the interrupt, that is, the wait state of the break thread. It is also said that when two threads pass through lock.lockinterruptibly () to acquire a lock, if thread A acquires a lock at this point, and the thread b only wait, then call the threadb.interrupt () method on thread B to be able to break thread B the waiting process.

Note that when a thread acquires a lock, it is not interrupted by the interrupt () method.

therefore , when a lock is acquired through the lockinterruptibly () method, it can be interrupted if it cannot be obtained and only waits.

and with synchronized modification, when a thread waits for a lock, it cannot be interrupted, only waiting. Reentrantlock

using the lock interface directly, we need to implement a lot of methods, not very convenient,reentrantlock is the only implementation of the lock The class of the interface , and Reentrantlock provides more ways to Reentrantlock , which means " can be re-entered lock ".

High concurrency programming for Java

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.