1.2: Multithreaded

Seven, multithreading

JAVA how to ensure thread safety? Specifically how to use the lock in the project? Thread safety is reflected in three aspects

1.原子性:提供互斥访问,同一时刻只能有一个线程对数据进行操作, (atomic,synchronized);
2.可见性:一个线程对主内存的修改可以及时地被其他线程看到, (synchronized,volatile);
3.有序性:一个线程观察其他线程中的指令执行顺序,由于指令重排序,该观察 结果一般杂乱无序,(happens-before原则)。

How to ensure atomicity 1.Java: common synchronization lock and ensure atomicity operation of Java tools and the lock synchronization method (or a sync block). Using the lock, you can ensure the same time only one thread can get the lock, it ensures the same time only one thread can execute code between the application and release locks. Similarly the lock synchronization method or synchronized block. When using synchronous non-static method, the current instance is locked; using static synchronization method is locked Class object class; using a static block, the object is locked in parentheses behind synchronized keyword. Whether using locks or synchronized, the essence is the same, to achieve exclusive resources through the lock, so that the actual target code segment at the same time only one thread is executed, thus ensuring atomicity target code segment. This is a way to sacrifice performance for the price.

How 2.Java ensure visibility: Java provides the volatile keyword to ensure visibility. Since the JMM is a problem shared memory to achieve thread communication, so there will be based cache coherency. When modifications must be from a variable using volatile, it will ensure that the variable changes are immediately updated in memory, cache and other caches that variable is set to be invalid, so other threads need to read the value main memory read to get the latest value.

How 3.Java guarantee the order of: the compiler and processor to reorder instructions, will ensure consistent implementation of the results and the results of the code sequence reordered, so reordering process does not affect the execution of single-threaded program, but it may affect the accuracy of concurrent execution of multi-threaded programs. Java can guarantee the order of a certain procedure by volatile, also can be used to ensure sequential and synchronized through the lock. synchronized and lock guarantee the principle of order and ensure atomicity, it is by ensuring the same time there will only be one thread execution of the target code segment to achieve. Apart from the application level to ensure that the order of execution of the target code segment of the outer, JVM is also referred to as happens-before by the principle of sequential implicitly guaranteed. As long as the order of execution of two operations can be derived by happens-before, the JVM will ensure sequential, whereas their order JVM makes no guarantee, can be arbitrarily reordering necessary to obtain high efficiency.

What is thread-safe, how to ensure thread safety, what are the three principles thread-safe?

Java Concurrency - Introduction thread-safe and settlement mechanism

There is no other way to ensure thread safety?
Have. As far as possible to avoid non-thread-safe conditions - shared variable. If from the design to avoid the use of shared variables, you can avoid the occurrence of non-thread-safe, there is no need to lock or by synchronized and volatile resolve atomicity, visibility and order issues.
There are immutable objects can be modified using the final target thread-safe, because the final modified reference variable (except String) immutable are references to immutable, but it points to an object is variable, so these must be safe release, that can not be made final offers can modify the object's interface. Lock usage scenarios in the project?

JAVA how to avoid deadlocks?

Avoid deadlock
prepare a deadlock will result code is as follows:
1, the sequence when a plurality of locking threads requires some of the same lock, but in a different order locking, a deadlock occurs easily. If you can make sure that all the threads are to acquire a lock in the same order, then the deadlock will not occur.

2, the locking time Another way to avoid deadlock is trying to acquire the lock when adding a timeout, which means that in the process of trying to acquire the lock in exceeds this limit then give up the thread of the lock request . If a thread is not within a given time frame successfully obtain all the required locks, will be rolled back and release all locks have been acquired, and then wait for a random time and try again. This random wait time for other threads have the opportunity to try to obtain the same locks, and let the application at the time did not get the lock can continue to run (Translator's Note: After the first lock timeouts can do some other things continue to run again logic locked back before repeated).

3, deadlock detection deadlock detection is a better deadlock prevention mechanism, it is mainly for those who can not achieve sequential lock and lock timeout is not feasible scenario. Whenever a thread acquires the lock, the thread will lock and associated data structure (map, graph, etc.) to write down. In addition, whenever a thread requests a lock, this also needs to be recorded in the data structure. When a thread requesting the lock fails, this thread can traverse the lock graph to see if there is a deadlock occurs. So when detecting deadlocks, these threads what to do about it? One possible approach is to release all locks, back to back, and wait for retry after a random period of time. This and similar simple lock timeout, not only as a deadlock has occurred only fallback, but will not be locked because the request timed out. Although rollback and wait, but if you have a large number of threads to compete with a number of locks, they still repeatedly deadlock (Editor's note: Timeout with similar reasons, not reduce competition fundamentally).
A better solution is to set priorities for these threads, make a (or several) thread retirement, as did the rest of the thread deadlock continues as they need to maintain a lock. If the priority given to these threads is fixed, with a number of threads you will always have a higher priority. To avoid this problem, you can set random priority when a deadlock occurs.

Review the way the operating system deadlock:
Deadlock Prevention: restrictions to apply:
mutually exclusive: original exclusive resources become shared program may cause uncertainty.
Occupancy and wait: it must ensure that when a process requests a resource, it does not hold any other resources. (Either all get, or is not occupied) need to process the request and assign all of its resources, allows a process to request resources if and only if resource utilization is low when the process does not occupy any resources before it begins execution, starvation can occur without If the process to seize possession of certain resources, and to request additional resources can not be allocated immediately, release the resources currently occupied be preempted add resources to the resource list only if it can get old resource and new resource requests it, the process It can be implemented.

Circular wait: to sort all resource types, and require that each process in order to apply the resources.
Deadlock Avoidance: banker's algorithm, if it is found after the allocation of resources could deadlock, not the allocation of resources.
Deadlock detection: allows to enter a deadlock state, mainly through the detection algorithm to see whether or not a deadlock, then let the corresponding thread to be rolled back.
Deadlock recovery: kill all processes, or kills part of the process according to the priority, to release the deadlock.

ThreadLocal specifically how to use? In what the scene?

A thorough understanding of ThreadLocal
ThreadLocal- depth interview will be asked to resolve

When using ThreadLocal variable maintenance, ThreadLocal provided for each thread using the variable independent variable copy, each thread can independently change their copy without affecting other threads corresponding copy. From the perspective of the thread of view, the target variable is like a thread local variable, which is meant to express the class name "Local". How do ThreadLocal is to maintain a copy of each thread variables it? In fact, the idea is very simple realization: There is a Map in ThreadLocal class, a thread for each copy of the variable storage, key elements in the Map is thread object, and the value of the variable corresponding to a copy of the thread. ThreadLocal from another point of view to solve the multi-threaded concurrent access. ThreadLocal will provide a copy of the independent variables for each thread, thereby isolating the conflict on multiple threads access the data. Because each thread has its own copy of the variable, so there is no need for the variable sync. ThreadLocal provide a thread-safe shared objects, when writing multithreaded code can be encapsulated into the unsafe variables ThreadLocal. Personal understanding: each ThreadLocal interior has a static inner class: variable copy ThreadLocalMap, Map inside the store thread-local thread object (key) and threads (value), however, the internal Thread Map by ThreadLocal maintained by ThreadLocal accountable to the map get and set the value of the variable thread. So for the different threads, each time you get a copy of the value, other threads can not get to a copy of the current thread's value, a copy of the form isolation, without disturbing each other.

Use Scenario: Remember the scene Hibernate's session get it?

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<S ession>();
  //获取Session 4 public static Session getCurrentSession(){
  Session session = threadLocal.get(); 
  //判断Session是否为空,如果为空,将创建一个session,并设置到本地线程变量中 
    try { 
        if(session ==null&&!session.isOpen()){ 
            if(sessionFactory==null){ 
                rbuildSessionFactory();
                // 创建Hibernate的SessionFactory 
            }else{ 
                session = sessionFactory.openSession(); 
            } 
        } 
      threadLocal.set(session); 
      } catch (Exception e) { 
      // TODO: handle exception18 }
       return session; 
    }

Why should access to the database each thread is an independent Session session?
If multiple threads share the same Session session, there may be other threads to close the connection, and then execute the current thread has been closed session exception occurs when submitted, the system becomes abnormally.
This way to avoid thread scramble Session, improve the safety of under concurrency.

As a typical scenario using the above ThreadLocal database connection management, session management, thread scenario applies only to a copy of the independent variables, if the variable is a globally shared, not suitable for use under high concurrency.
A scene own use:

@Component 
public class HostHolder { 
private static ThreadLocal<User> users = new ThreadLocal<User>();
    public User getUser() { 
        return users.get(); 
    } 
    public void setUser(User user) {
        users.set(user);  
    } 
    public void clear() { 
        users.remove();
    } 
 }

It is mainly used to determine whether the current user login. That some pages and other pages, such as posting needs to determine whether the current user logged in, you need to log in if not jump to the login page.

Summary:
Each ThreadLocal variable can store only one copy of a thread on the line if you want to be able to save multiple copies of the above, you need to create multiple ThreadLocal.
ThreadLocal internal ThreadLocalMap key is weak references, there will be the risk of memory leaks. Applicable to non-state, high concurrency scenarios copy of the variable does not affect the separate business logic.
If the business logic strongly dependent on the copy of the variable, not suitable for use ThreadLocal to address the need to find another solution.

Guess you like

Origin www.cnblogs.com/HelloXTF/p/12099881.html