Summary of Java concurrency Knowledge points

Source: Internet
Author: User
Tags volatile

An important feature of the Java language is the built-in support for concurrency, which makes Java very popular with businesses and programmers. At the same time, if you want to improve your own technology, Java concurrency knowledge is essential, here is a simple collation of some relevant content, hope can play a role.

What is the 1,java memory model?

The Java memory model prescribes and directs Java programs to behave in a deterministic manner between different memory architectures, CPUs, and operating systems. It is especially important in the case of multithreading. The Java memory model guarantees that changes made by one thread can be visible to other threads, and that they are first-rate. This relationship defines rules that allow programmers to have a clearer idea of concurrent programming. For example, prior sex ensures that:

The code within the thread can be executed in a sequential order, which is called the program order rule.

For the same lock, an unlock operation must occur after another lock operation that occurs after the time, also known as a pipe lock rule.

The previous write to volatile is also called a volatile variable rule before the next volatile read operation.

Any operation within a thread must be called after the start () Call of this thread, also known as the thread initiation rule.

A thread terminates the rule before all operations on a thread are terminated.

The end operation of an object must also be called an object finalization rule after the object is constructed.

Transitivity

More introduction to the Concurrent Programming network:

(In-depth understanding of the Java Memory Model Series article: http://ifeve.com/java-memory-model-0)

What is the difference between interrupted and Isinterruptedd methods in 2,java?

The main difference between interrupted () and isinterrupted () is that the former clears the interrupt state and the latter does not. The Java Multi-threading interrupt mechanism is implemented with an internal identity, and calling Thread.Interrupt () to break a thread sets the interrupt ID to true. The interrupt state is zeroed when the interrupt thread calls the static method thread.interrupted () to check the break state.

A non-static method, isinterrupted (), is used to query the interrupt state of other threads without changing the interrupt status identifier. Simply put, any method that throws a Interruptedexception exception will clear the interrupt state. In any case, the interrupt state of a thread can be changed by other threads calling interrupts.

What is the difference between a synchronous collection in 3,java and a concurrent collection?

Both synchronous and concurrent collections provide the appropriate thread-safe collection for multithreading and concurrency, although the concurrency collection is more extensible. Before Java1.5, programmers had only synchronized sets to use and in the multi-threaded concurrency will lead to contention, hindering the system's extensibility. JAVA5 introduces concurrent collections like Concurrenthashmap, which not only provides thread safety but also improves scalability with modern technologies such as lock separation and internal partitioning.

Whether it's synchronous collections or concurrent collections they all support thread safety, and the main differences between them are performance and scalability, and how they implement thread safety.

Synchronous HashMap, Hashtable, HashSet, Vector, ArrayList compared to their concurrent implementations (Concurrenthashmap, Copyonwritearraylist, Copyonwritehashset) is much slower. The main cause of this slowness is the lock, which locks the entire map or list, while the concurrent collection does not. Concurrent collections implement thread safety by using advanced and sophisticated techniques like lock stripping.

For example, Concurrenthashmap will divide the entire map into fragments, lock only the relevant fragments, and allow multiple threads to access other unlocked fragments.

Similarly, Copyonwritearraylist allows multiple threads to read in an unsynchronized manner, and when the thread is written it copies the entire list to it.

This can be more scalable than using synchronous collections if you are using concurrent collections under conditions that are beneficial to concurrent collections, such as read more write less.

4, what is a thread pool? Why use it?

Creating threads takes expensive resources and time, and if the task is to create a thread, the response time is longer and the number of threads a process can create is limited. To avoid these problems, when the program starts, it creates several threads that respond to processing, called the thread pool, which is called a worker thread. Starting with JDK1.5, the Java API provides a executor framework that allows you to create different thread pools. For example, a single thread pool, one task at a time, a fixed number of thread pools or a pool of cache threads (an extensible thread pool for programs that are suitable for many short-lived tasks)

The role of the thread pool is to initialize a certain number of threads at the time the thread is called, and when the thread comes over, it detects that the initialized threads are empty, and does not see whether the number of threads currently running has reached the maximum number, and if not, a new thread is allocated for processing.

Just like eating in a restaurant, call a waiter out of the house, but if you have reached the maximum number, it is equivalent to the waiter has been exhausted, there is no way, the other thread will only wait until there is a new "waiter" so far.

The advantage of the thread pool is that it can manage threads and have a high hub so that the program does not mess up and that the system will not be hung up because of a lot of concurrency and insufficient resources.

What is the difference between a live lock and a deadlock in a 5,java?

Live Lock: A thread typically has activities that respond to other threads. If other threads also respond to the activity of another thread, a live lock can occur. As with a deadlock, the thread that made the life lock cannot continue execution. threads, however, are not blocked-they are busy responding to the other person's inability to resume work. This is the equivalent of two people who meet in the corridor: A to his own left by want to let B past, and B to his right side by want of a past. It is visible that they have blocked each other. A to his right, and B to his left, they still blocked the other side.

Deadlock: Two or more threads block locks that are held by threads waiting for other deadlock states. Deadlocks usually occur when multiple threads are simultaneously requesting the same set of locks in different order, and deadlocks can cause your program to hang without completing the task.

6, how to avoid deadlocks?

The following four conditions must be met for a deadlock to occur:

Mutex condition: A resource can only be used by one process at a time.

Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.

Non-deprivation: the resources that the process has acquired cannot be forcibly stripped until the end of use.

Cyclic wait condition: a cyclic waiting resource relationship is formed between several processes.

Three techniques to avoid deadlocks:

Lock order (threads locking in a certain order)

Lock time limit (when a thread attempts to acquire a lock with a certain time limit, the request for the lock is discarded and the lock is freed)

Deadlock detection

(Cause of deadlock and how to avoid a deeper understanding: http://blog.csdn.net/ls5718/article/details/51896159)

What is the difference between 7,notify () and Notifyall ()?
Both 1,notify () and Notifyall () are methods that object objects are used to inform the thread that is waiting for the object.
2,void notify (): Wakes up a thread that is waiting for the object.
3,void Notifyall (): Wakes up all threads that are waiting on the object.
The biggest difference between the two is:
Notifyall causes all threads that originally wait on the object to be notify to exit the wait state, becoming a lock on the object, and once the object is unlocked, they compete.

Notify he just chooses a wait-state thread to notify, and it gets the lock on the object, but does not disturb other threads that are also waiting to be notify by the object, releasing the lock on the object when the first thread finishes running, and if the object does not use the Notify statement again, Even if the object is idle, the other waiting-state waits for the thread to remain in the wait state until it emits a notify or notifyall, and waits for a notify or notifyall instead of a lock, because the object is not notified.

8, what is a reentrant lock (reentrantlock)?

The lock framework in Java.util.concurrent.lock is an abstraction of locking, which allows the implementation of a lock to be implemented as a Java class, rather than as a language feature.            This leaves space for the various implementations of lock, which may have different scheduling algorithms, performance characteristics, or locking semantics. The Reentrantlock class implements lock, which has the same concurrency and memory semantics as synchronized, but adds features like lock polling, timed lock-in, and interruptible lock waiting. In addition, it provides better performance in the case of intense contention. (In other words, when many threads are trying to access a shared resource, the JVM can spend less time dispatching the thread and more of it to the execution thread.) )
What does the reentrant lock mean? Simply put, it has a lock-related get counter, if one of the threads that owns the lock gets the lock again, then the fetch counter increases by 1, and then the lock needs to be freed two times to get a true release. This mimics the semantics of synchronized; If a thread enters a synchronized block that is protected by a monitor that the thread already owns, it allows the thread to continue and does not release the lock when the thread exits the second (or subsequent) synchronized block. The lock is released only when the thread exits the first synchronized block that the monitor protects when it enters.

9. What application scenarios can read and write locks be used for?
Read-write locks can be used for "read and write less" scenarios, read and write locks support multiple read operations concurrently, and write operations can only be performed by a single thread
Readwritelock is optimized for situations where data structures are written relatively infrequently, but there are multiple tasks that are frequently read by this data structure. Readwritelock allows you to have multiple readers at the same time, as long as they are not trying to write. If a write lock is already held by another task, no reader can access it until the write lock is released.
Readwritelock the improvement of program performance is mainly subject to the following factors:
1, the frequency at which the data is read is compared with the modified frequency.
2, read and write time
3, how many threads are competing

4, whether to run on a multi-processing machine

Transfer from http://www.cnblogs.com/peke/p/7912907.html

Summary of Java concurrency Knowledge points

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.