Java Concurrency Summary-Basic article

Source: Internet
Author: User
Tags java se


Multithreading 1. There are several ways to implement a thread in Java?
inheriting the thread class, implementing the Runnable interface the only way to create a thread is to instantiate the Java.lang.Thread class (or its subclasses) and call its start () method
2. How do I stop a running thread?
Call the Threadinstancea.inerrupt () method so that when the a thread is sleep,join the thread's method, or the wait method of object, it throws the inerruptedexception directly, and then exits after snapping.
public void shutdown() {stop = true;this.interrupt();try {this.join();}catch(InterruptedException ie) {}}
The best way to stop a thread is to let it execute, there is no way to stop a thread immediately, but you can control when or under what conditions to let him finish. Control the execution of a thread through a conditional variable, check the state of the variables inside the thread, and change the value of the variable externally to control stop execution. To ensure instant communication between threads, you need to use the volatile keyword or lock to ensure that the read thread is consistent with the state of the variable between the write threads. Here's a template:
public class BestPractice extends Thread {private volatile boolean finished = false; // ① volatile条件变量public void stopMe() {finished = true; // ② 发出停止信号}@Overridepublic void run() {while (!finished) { // ③ 检测条件变量// do dirty work // ④业务代码}}}
When the code at ④ is blocked by wait () or sleep (), the thread cannot immediately detect the condition variable. So the code at ② is best to call the interrupt () method at the same time as the top. From the source view of the join is also called wait, so how did he do "thread B in the join () method is called, until thread a finishes execution, will continue to execute thread B"? Wait () frees the lock on the object, and the thread waiting to get the lock has an essential difference from the thread that calls wait, and once a thread calls the Wait method, he enters the wait set and the thread cannot immediately unblock when the lock is available. He maintains the blocking state until another thread calls the Notifyall/notify method of the same lock, and in B calls A.wait, where a is the object that provides the monitor (the provider of the lock), and B is the really blocked thread (the user of the lock). So thread B stops at the point where the code executes a.join, and because no other thread calls A.notify to end the block, it waits until the a thread finishes executing, and when a thread ends, he releases all locks on the object immediately, and the B thread proceeds from the next line of A.join. If you want to break this mechanism, you can call A.interrupt (), at which point thread B does not have to be constrained by just
3. What is the difference between notify () and Notifyall ()?
The
x.notify () method wakes one of the other threads in wait on the X object (only one in the waiting thread is awakened, which thread is awakened by the JVM), and the X.notify () method wakes all the threads that wait on the X object. However, because you want to continue executing the code after wait, you must obtain a lock on the corresponding X object in the sychronized block, so once one thread obtains the lock, the other thread waits for the other thread to release the lock and then to continue execution. Notify is prone to deadlock, when only one thread is active and is going to wait, if calling notify wakes up another blocked thread because it wakes up only one thread, if the wake-up thread discovers or does not satisfy the condition, it is possible that all the threads are blocked. Cause a deadlock.
4. What is the difference between sleep () and wait ()?
sleep does not yield a lock, and wait will yield the lock.
5. What is a daemon thread? What is the point of it?
user thread: Is the normal thread that we normally create. Daemon: Primarily used to service user threads. Check the status of the system regularly. The JVM exits when the thread is left with only the daemon. But if any other user thread is still there, the JVM will not exit.
6. How does Java enable communication and collaboration between multiple threads?
the so-called thread communication, refers to the sending of signals to wake up another thread, generally used in the case of the existence of a thread mutex. Use can choose Object.wait,object.notify/notifyall, with sychronized keyword. You can also choose the concurrent package provided, lock (Reetrantlock), Condition (Lock.newcondition ()), after Lock.lock acquired the lock through Condition.await (), Condition.signal/signalall to enable collaboration between threads
Lock 7. What is a reentrant lock (reentrantlock)?
The
concurrent package provides a display lock object that replaces the monitor in object. Inherits the child lock interface, which is used to protect code from the lock () method to the critical area of unlock (). The Mate Condition Object (Condition) is used. Condition gets access to the critical code by obtaining Reentrantlock.
8. When a thread enters an synchronized instance method of an object, does the other thread have access to other methods of this object?
an Synchronize instance method of an object is equivalent to sychronized (this) in a common strength method, which occupies the lock of the current object, at which point other threads cannot access the object's additional synchronize instance method, However, you can access other non-synchronous methods.
9. What are the similarities and differences between synchronized and Java.util.concurrent.locks.Lock?
The
basic function is the same, all to solve the problem of mutual exclusion between threads. The implicit lock and condition (synchronized,wait,notify) approach, while writing code to be concise, has some drawbacks:-you can't break a thread that is trying to get a lock. -Cannot set timeout when trying to acquire lock-only one condition per lock, sometimes not enough (e.g. read-write lock problem) the lock and condition shown (reetrantlock,condition) solves several problems with the implicit lock above: The-lock method cannot be interrupted, So the Trylock method is provided for lock testing and timeout-by calling the Trylock method with timeout, if the thread waits for a lock to be interrupted, a Interruptexception exception is thrown to break the deadlock. -You can also call the Lockinterruptibly method, which is equivalent to a timeout set to an infinite Trylock method. -The await method also provides time-out settings for read-write lock issues: When the read-write-less situation guarantees the acid of the data while improving the processing power of the system, only "read-read" can be unlocked. "Read-write", "write-read", "write-write" still need to lock. The Reentrantreadwritelock class is available in the concurrent package to help create read and write locks. Readlock () Gets a read lock that can be shared by multiple read operations, but he rejects all writes. Writelock () Gets a write lock that rejects all other read and write operations. In addition, the display lock also provides fairness and other features.
10. Optimistic locking and pessimistic lock understanding and how to achieve, what is the way to achieve?
Pessimistic lock that every time the data are taken by others can be modified, so each time the data need to lock, so that other people want to take the data will be block, until they release the lock. The implementation can take advantage of the Object.wait/notify mate synchronized described earlier, or the Lock.lock mate Condition.await/signal provided by the concurrent package. Optimistic lock that the data will not be modified, so when the data are not locked, but in the back to write the data when the time to confirm whether someone updated this data, you can use the version number and other mechanisms. It can improve the throughput of the program if it is suitable for many read and write less. If write more is prone to data inconsistency caused retry, but inefficient. The implementation can be in CAS (check-and-set) or use volitate variables.
Java demoAtomicInteger atom = new AtomicInteger(1);boolean r = atom.compareAndSet(1, 2);
Concurrency framework What is the difference between Synchronizedmap and concurrenthashmap?
The
HashMap version of Synchronizedmap is inefficient, and the map interface itself provides Keyset,values,entryset, which provides a view rather than a copy, so when a thread is iterating over the elements in the map, Another thread may be modifying an element within it. At this point, the concurrentmodificationexception exception may be thrown when iterating over an element. CONCURRENTHASHMAP implements the Concurrentmap interface, Concurrenthashmap uses a segmented locking design, and different threads do not cause blocking. It is only necessary to lock the entire table when the size is in operation, which greatly improves the efficiency.
What application scenarios can copyonwritearraylist be used for?
suitable for reading a lot of very few scenes, such as some personnel information, parameter configuration and so on will often be read, but rarely modified situation.
Thread Safety 13. What does thread safety mean? is the servlet thread-safe ?
Reference Concept: If your code is in a process where multiple threads are running concurrently, these threads may run this code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. I understand that thread safety is caused by global variables and static variables, either multithreading does not access the same data, or using mechanisms to ensure the security of the same data access (such as the operation of the data is atomic operations, locking mechanisms, including pessimistic locks and optimistic locks). A servlet is multithreaded, and a Servlet implementation class has only one instance object, which is singleton, so multiple threads may access the same Servlet instance object, but that doesn't mean the servlet is thread insecure. Whether a servlet is thread-safe is determined by its implementation, and if its internal properties or methods are changed by multiple threads, it is thread-safe and vice versa.
14. How does synchronization have several implementations?
Lock, join, block queue
What is the use of volatile? Can you describe the volatile application scenario in a sentence?
The definition of volatile in the
third edition of the Java Language specification is as follows: The Java programming language allows threads to access shared variables, and in order to ensure that shared variables can be updated accurately and consistently, the thread should ensure that the variable is obtained separately through an exclusive lock. The Java language provides volatile, which in some cases is more convenient than a lock. If a field is declared as a Volatile,java thread, the memory model ensures that all threads see that the value of this variable is consistent. The volatile keyword provides a lock-free (lock-free) mechanism for synchronizing access to an instance's domain. If you declare a domain as volatile, the compiler and the virtual machine know that the domain may be updated concurrently by another thread. There are fewer domain values in the object that need to be synchronized, and the use of locks appears wasteful and cumbersome, when volatile is used. Volatile is used within the implementation of some concurrent containers (CONCURRENTHASHMAP,ETC). Using the Happen-before principle of the JVM to the volatile promise, complete the non-locking concurrent read and write.
16. Please describe the memory model and workflow of the following Java.
Memory model: Java memory model on JVM specification, Java SE 7 Edition, and mainly in the chapters "2.5 Runtime Data areas" and "2.6 Frames" Detailed instructions are available. The data for objects and classes is stored in 3 different memory areas: heap (heap space), method area, local region (native area). The heap memory holds the object and the data of the array, the method area holds the class information (including the class name, method, field), static variables, compiler compiled code, the region contains thread stacks, local method stack and other storage threads. The method area is sometimes referred to as the Persistence generation (PermGen), which is mainly due to the fact that the early hotspot uses the method area to implement the persistence generation, which of course brings some problems, which are not essentially a concept. All objects are stored in heap memory for the entire run-time period after instantiation. Heap memory is also divided into different parts: Eden (Eden), Survivor Area (Survivor sapce), old Generation Space. The execution of the method is accompanied by a thread. Local variables and references for the original type are stored online stacks. Objects that refer to associations, such as string, exist in the heap. Heap memory is also divided into multiple zones:
  • New Generation (young Generation) containing Eden (Eden) and Survivor area (Survivor Sapce)
  • Old Age (Generation)
the objects stored in different regions have different lifecycles: Workflow: New or short-term objects are stored in the Eden area, and surviving or medium-term objects are copied from the Eden region to the Survivor region; An always-on or long-term object will be copied from survivor to old Generation, and the life cycle of the object can consume a short time and CPU to do a small garbage collection (GC). The reason is that, like C, the release of memory (by destroying objects) is achieved through 2 different GC implementations: Young GC, full GC. To check that all objects can be destroyed, young GC flags objects that cannot be destroyed, and after multiple tokens, the object will be moved to the old age.
17. Why does the code re-order?
JMM allows the compiler, runtime, processor, or cache to have privileged timing to deposit or remove variable values at the specified memory location of a variable. For example, in order to optimize a cyclic index variable, the compiler may choose to store it in a register, or the cache will be deferred to a more appropriate time before a new variable value is stored in main memory. All of these optimizations are designed to help achieve higher performance. The term "reordering" is used to describe several types of memory operations:
  • When the compiler does not change the semantics of the program, as an optimization it can arbitrarily reorder certain instructions.
  • In some cases, you can allow the processor to perform some operations in reverse order.
  • Caches are usually allowed to store variables in main memory in the same order as they were written by the program.
Reference list:
  • "JAVA2 Core Technology-Volume 2: Advanced Features"
  • Java Concurrency Programming Practice
  • http://ibruce.info/2013/12/17/how-many-ways-to-create-a-thread-in-java/

Java Concurrency Summary-Basic 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.