Multithreading face questions Highlights

1, Why Executor framework?

Each time you create a thread new Thread () compare consumption performance (time-consuming and resource-consuming), and the task was to create a so response time will be longer. Convenient recycling thread pool threads, created to avoid frequent cause of resource consumption

new Thread () thread creation of lack of management, but also can create unlimited, competition between threads can lead to excessive system resources and cause the system paralysis (OutOfMemoryError, OOM), there will be alternating frequently between threads consume a lot of system resources. Executors create a thread can effectively control the maximum number of concurrent threads, improve utilization of system resources, while avoiding excessive competition for resources

new Thread () start thread is not conducive to expansion, such as the timing of execution, performed regularly interrupted thread so inconvenient to achieve (a thread pool to provide regular periodic execution, single-threaded, concurrent control, etc. )

2 difference, Executor and Executors of

Executors are tools, which process can create various types of thread pools (fixed length, variable length, timing single)

Executro root interface is a thread pool, which has an execute () method is used to perform tasks

3. What is an atomic operation? DESCRIPTION atoms class java.util.concurrent package?

Atomic operation (atomic operation): one or a series of operations can not be interrupted.

The processor used to implement atomic operations between the multiprocessor cache based approach locking or bus locked.

In Java can be implemented by an atomic operation and locking manner CAS cycle. CAS operation (Compare and swap or compare and set), now almost all cpu instructions support of atomic operations cas

Refers to an atomic operation is not otherwise affect the operation of the operation unit task. Atomic operations to avoid data inconsistency means to be in a multithreaded environment

int ++ is not an atomic operation, so when a thread reads its value and add a time, another thread might have read previous value, which raises an error

To solve this problem, we must ensure that the increase operation is atomic, JDK1.5 before we can use the synchronization techniques to do this. 1.5 java.util.concurrent.atomic package offers increased long int types of atoms and packaging, for they can ensure their operation is atomic, but does not require synchronization.

java.util.concurrent.atomic atoms inside the package type, the basic feature is in a multi-threaded environment, threads when multiple instances of these classes to perform a method comprising having exclusive: that is, when the thread enters a method, performed instruction which will not be interrupted by other threads, and other threads like spin locks, wait until the completion of the implementation of the method, before choosing another thread from the queue waiting to enter by the JVM, this is just the kind of logic understanding.

- Atom: AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference

原子数组:AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray

Attribute atomic updater: AtomicLongFieldUpdater, AtomicIntegerFieldUpdater, AtomicReferenceFieldUpdater 

ABA to solve the problem of atomic categories: AtomicMarkableReference (boolean reflected by introducing a middle not changed) (int accumulate the intermediate reflected by introducing one has not changed)

4. Lock interfaces are what? Contrast synchronized What are the advantages?

Lock interface provides a lock operation more scalable than synchronized

Advantage:

  Fair locks

  The thread can interrupt response time of waiting for the lock

  It allows thread tries to acquire the lock (tryLock) and returns immediately when unable to obtain the lock or wait for some time

  Can, acquiring and releasing locks in a different order in a different range

Lock are synchronized on the whole of the expansion board, provided unconditional Lock, pollable (tryLock method), timing (tryLock parameterized), interruptible (lockInterruptibly in), the condition can be more queues (new Condition Method) lock operation. In addition Lock implementation class basic support non-equity (default) and fair locks. synchronized only support non-fair locks, of course, in most cases, non-lock is fair and efficient choice

5, Executors framework

 Excutors frame is performed according to a side of a set of calls, the frame asynchronous tasks scheduling, execution and control.

Unlimited creating a thread may cause application memory overflow. So create a thread pool is a better solution, because you can limit the number of threads and can be recycled these threads. Using Executors frame can be very easily create a thread pool (fixed length, variable length, single timing)

6, what is blocking queue (BlockingQueue)? What is the realization of the principle of blocking queue? How to use blocking queue to achieve producer - consumer model

Blocking queue (BlockingQueue) is a support for two additional operations queue.

These two additional operations are: the queue is empty, obtain the thread elements will wait for the queue to become non-empty. When the queue is full, the thread will wait queue storage elements available.

Blocking queue common language producers and consumers scenes, producers are added to the queue thread elements, the consumer is to take elements from the queue thread. Blocking queue storage container element is the producers, and consumers only take elements from the container.

JDK7 offers 7 blocking queue. They are:

  ArrayBlockingQueue: an array of structures bounded blocking queue

  LinkedBlockingQueue: a linked list of structures bounded blocking queue

  PriorityBlockingQueue: a support prioritization of unbounded blocking queue

  DelayQueue: Use a priority queue unbounded blocking queue implementation

  SynchronousQueue: a storage element not blocking queue (this 5 jdk 1.5)

  LinkedTransferQueue: a list structure by blocking unbounded blocking queue (jdk1.7)

  LinkedBlockingDeque: a list structure consisting of a bidirectional blocking queue (JDK1.6)

When synchronized access before 5 java, you can use a set of common, then the use of threads and thread synchronization can be achieved in collaboration producer, consumer model, the main technology is good use: wait, notify, notifyAll, synchronized these keywords . And after java 5, can be used to achieve blocking queue, this method greatly reduces the amount of code, making it easier to multi-threaded programming, security is also guaranteed.

Queue BlockingQueue interface is a sub-interface, its main purpose is not as a container, but as a tool to thread synchronization, it has an obvious feature, when the producer thread into mentoring BlockingQueue like element, if the queue is full, the thread is blocked, when the consumer thread removed from a mentoring element, if the queue is empty, the thread is blocked, precisely because it has this feature, so multiple threads in the program alternates BlockingQueue placed element, the element removed, it can be well controlled communication between threads.

Blocking queue to use the classic scenario is to read and parse socket client data, the data read thread continue to put data into a queue, and then continue to resolve thread from the queue data analysis

 7. What is the Callable and Future?

Callable interface is similar to Runnable, but Runnable no return value, and can not throw exceptions (run method can not declare an exception). Callable interfaces, the method allows the call returns a value (and may declare the exception), the return value may be get Future.

It could be considered with a callback Runnable

Future interface represents asynchronous tasks, future results have not yet completed the task given. So Callable used to produce a result, Future for obtaining results

8. What is FutureTask?

FutureTask task represents an asynchronous operation to achieve the Future and Runnable interface Callable hold of reference. Meaning it can be passed to Thread (Runnable task), call the start () method to start a thread, and can obtain the return value of the results of threads. Executors of course, can also use the thread pool by submitting the job.

public  static  void main (String [] args) {
     // a first embodiment 
    ExecutorService Executor = Executors.newCachedThreadPool ();
    Task task = new Task();
    FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
    executor.submit(futureTask);
    executor.shutdown();
     
    // second embodiment, note that in this manner and achieve a similar way, but using a ExecutorService, one using the Thread 
    / * the Task Task the Task new new = ();
    FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
    Thread thread = new Thread(futureTask);
    thread.start();*/
     
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e1) {
        e1.printStackTrace ();
    }
     
    System.out.println ( "main thread on a mission" );
     
    try {
        System.out.println ( "Task Run Results" + futureTask.get ());
    } catch (InterruptedException e) {
        e.printStackTrace ();
    } catch (ExecutionException e) {
        e.printStackTrace ();
    }         
    System.out.println ( "finished all tasks" );
}

 

9. What is concurrency container?

Synchronous container: container is to achieve synchronization by synchronized. If there are multiple threads call method synchronized container, they will serial execution. Such as Vector, HashTable, Collections.synchronizedSet, synchronizedList return the like containers. The method of these containers are generally used to modify synchronized (including reading)

Synchronizing concurrent containers using the container with different locking strategies to provide higher concurrency and scalability, for example with a finer granularity locking mechanism (lock segment) in ConcurrentHashMap, the locking mechanism in such Permission is granted to any number of read threads concurrently access the map, and execute access map thread and write threads read operation also can be complicated, while allowing write thread a certain number of concurrently modified map, so it can be the environment in concurrent under higher throughput

10, CyclicBarrier and CountDownLatch What is the difference?

1) CountDownLatch a thread to wait to know his other threads are waiting for the completion and implementation of call countDown () method to be notified when the current thread to continue execution

2) CyclicBarrier all threads waits until all threads are ready to enter the await () method after all threads started

3) CyclicBarrier reusable (reset ()), but can not be reused CountDownLatch. So CyclicBarrier can handle more complex business scenarios, such as if calculation error occurs, you can recharge counter thread to execute them once again.

4) CyclicBarrier also provides other useful methods, such as getNumberWaiting ways to get the number of threads CyclicBarrier blocked. isBroken method is used to know whether the blocked thread is interrupted.

Java's concurrent package inside CountDownLatch In fact, it can be seen as a counter, but the operation of this counter is an atomic operation, while only one thread to operate the counter, that is, at the same time only one thread to reduce the counter inside value.

You can set an initial target to CountDownLatch number as a count value, any call this object the await () method will be blocked until the count value of the counter is reduced by another thread reaches zero.

So before the current count reaches zero, await method would have been to block. After that, will release all waiting threads, all subsequent calls will await return immediately. This phenomenon occurs only once - count can not be reset. If you need to reset the count, consider using CyclicBarrier.

A very typical scenario CountDownLatch is: there is a task you want to perform down, but must wait until the other task is finished you can continue down the implementation. If we want to continue to perform the task of calling down a awit CountDownLatch object () method, calling countDown other tasks on the same subject CountDownLatch After their task () method task, this calls await () method We will always block until the count value CountDownLatch object reduced to 0 so far.

CountDownLatch  :  a thread (or more), waiting for the other N threads to complete certain things that you can perform after.

CyclicBarrier : N threads wait for each other before any thread to complete, all threads must wait

CyclicBarrier is a synchronization aid that allows a set of threads waiting for each other to reach a common barrier point (common barrier point). Relates to a set of program threads fixed size, these threads must wait for each other from time to time, this time CyclicBarrier useful. Because the barrier after the release waiting threads can be reused, so we called him cycle barrier.

CyclicBarrier a typical usage scenario for multi-threaded computing the data, and merge the results

11, how to stop a running thread?

1) use shared variables: shared variable as a label

2) Use interrupt () method terminates threads: If a thread is waiting for some event to occur due is blocked, how should we do to stop this thread? This often happens, such as when a thread because of the need to wait for keyboard input is blocked, or call Thread.join () method, or Thread.sleep () method is called ServerSocket.accept () method in a network, or by calling when the DatagramSocket.receive () method, are likely to lead thread is blocked, the thread is not running when in the state, even if the shared variable in the main thread is set to true, but this time could not check the thread loop flag, Of course, it can not be interrupted immediately. It is recommended that we give is, do not use the stop () method, but using the interrupt () method of the Thread offer, because although this method does not interrupt a running thread, but it can make a blocked thread throw an interrupt exception, so that the thread ended prematurely blocked, blocked exit code.

12, optimistic and pessimistic locking and understanding of how to achieve, what are the implementation?

Pessimistic locks: always assume the worst case, each to data that others will think when they are modified, so the data will be locked each time to take the time, so people want to take this data will be blocked until the lock to get it . Traditional relational database inside to use a lot of this locking mechanism, such as row locks, table locks, etc., read lock, write lock, are locked before doing the operation. Another example is the synchronization of the synchronized keyword in Java which is actually pessimistic locking.

Optimistic locking: As the name suggests, is very optimistic, pick up data every time when they are that others will not be modified, so it will not be locked, but when the update will determine what others during this time did not go to update the data, you can use mechanism version number. Optimistic locking scenarios for applications to read, which can improve throughput, want similar write_condition mechanisms provided by the database, optimistic locks are actually provided. In Java java.util.concurrent.atomic package below the yard it is to use a class variable implementation of CAS implementation of optimistic locking.

Optimistic locking implementation:

  (1) to determine whether to use version represents the data when read data is consistent with the author. After submitting a modified version of identity, inconsistencies can take the discard policy and try again

  (2) Compare and swap in Java CAS i.e., when a plurality of threads simultaneously attempt to use the CAS update the same variable, only one thread can update the value of variables, while the other threads have failed, the failure will not be hanging thread on, but was told that the competition fails, and you can try again. CAS operation includes three operands - the need to read and write memory location (V), compared to the expected original value (A) and the new value (B) intended to be written. If the value of the original value and the expected memory location V A match, then the processor will automatically update the value to the new value B. Otherwise, the processor does nothing.

CAS Disadvantages:

  (1) ABA problem: For example, one thread removed from the memory location V A, which is also removed when another thread A two from memory, and carried out some operations into two to B, and the data of the two turn positions V becomes a, this time one thread perform the operation found that CAS is still in memory a, then a successful one operation. Although one thread of CAS operation is successful, but the problem there may be hidden. Provides a mine AtomicStampedReference from atomic bag Java1.5 JDK start to solve the problem of ABA

  (2) long cycle time overhead Large: For serious competition for resources (threads serious conflict) situation, the probability of CAS spin will be relatively large, thus wasting more CPU resources, efficiency is lower than synchronized

  (3) can only guarantee atomic operation of a shared variable: When performing operations on a shared variable, we can use the CAS cycle approach to ensure an atomic operation, but multiple shared variables from the operating cycle CAS can not guarantee operation atomicity, the lock can be used at this time.

13, SynchronizedMap and ConcurrentHashMap What is the difference?

SynchronizedMap use synchronized block to ensure thread safety lock for the current object.

ConcurrentHashMap use locks to ensure the performance of segmented multi-threaded.

ConcurrentHashMap is time to lock in a barrel. The default hash table ConcurrentHashMap into the tub 16, such as a common lock operating values ​​get, put, remove the need to use other current bucket. In this way, the original can only enter a thread, now able to write 16 execution threads to improve concurrency is obvious.

In addition ConcurrentHashMap use a different iterative manner. In this iterative manner, when then change the set after the iterator is created will no longer throw ConcurrentModificationException, replaced by new data when new change so as not to affect the original data, and then complete the iterator will replace the head pointer for the new data, so iterator original thread can use old data, and write concurrent threads can also complete change

14, CopyOnWriteArrayList application scenarios

One of the benefits (lock-free container) of CopyOnWriteArrayList is when multiple iterations simultaneously traverse and modify this list will not run out of ConcurrentModificationException.

In CopyOnWriteArrayList, a write results in the creation of a copy of the entire underlying array, the source array will remain in place, such that replicate in the array is modified, a read operation can be performed safely.

  (1) Due to the time of writing operation, you need to copy array consume memory, if the contents of the original array under the relatively large number of cases, it may lead to young gc or full gc;

  (2) can not be used for real-time reading of the scene, like a copy of the array, the new element will take time, so called after a set operation, the read data may still old, although CopyOnWriteArrayList can do eventual consistency, but still did not France meet real-time requirements;

CopyOnWriteArrayList said the idea: separate read and write; eventual consistency; the use of additional open space of ideas to resolve concurrency conflicts

15, what is thread-safe? servlet is thread safe?

Refers to a thread-safe function is called when the library in a multithreaded environment, able to correctly handle variable shared between multiple threads, make the program function properly completed.

Servlet is not thread safe, servlet make more than a single-threaded example, when multiple threads access the same method, thread safety is not guaranteed to shared variables.

16, volatile what's the use? Scenarios

ensure visibility and prohibits volatile memory instruction reordering

volatile for a single operation in a multi-threaded (single read or single write)

Five kinds of scenarios: state flag, a one-time security releases for independent observation, volatile bean pattern, cheap read - write lock strategy (Reference: https://www.ibm.com/developerworks/cn/java/j- jtp06197.html )

17, why the code reordering

When executing the program, in order to provide performance processor and compiler reorders instructions will often, but not free to reorder the need to meet the following two conditions:

(1) can not change the result of the program in a single-threaded environment

(2) does not permit the presence of reordering since the data relationships

Note that: reordering does not affect the results of a single-threaded environment, but will destroy the multi-threaded execution semantics

18, abnormal occurrence happens a thread running?

If the exception is not caught, the thread will stop execution

Thread.UncaughtExceptionHandler it is used to treat abnormal excuse not to capture an embedded thread cause sudden interruption of. When an uncaught exception will cause the thread interruption, JVM will use Thread.getUncaughtExceptionHandler () to query thread thread UncaughtExceptionHandler disease and abnormal passed as parameters to the uncaughtException handler () method for processing

19, why wait, notify and notifyAll these methods are not the Thread class, and in the Object class?

One obvious reason is that Java provides an object lock lock instead of thread-level, each object has a lock obtained by a thread. As the wait, notify, notifyAll are lock-level operations, so they are defined in the Object class, because the lock belonging to the object

20, what is the ThreadLocal variable?

ThreadLocal variable called threads, each thread has a ThreadLocal is that each thread has its own independent variables, conditions of competition are eliminated. It is a good way to get thread-safe for the creation of costly objects, for example, you can use ThreadLocal let SimpleDataFormat become thread-safe, because that class creates costly and each call to create different instances it is not worth it in the local area use it if offers its own unique variables for each thread copies, will greatly improve efficiency. First, by multiplexing reduces the number of costly creation of objects. Secondly, you do not get a thread-safe use synchronous or immutability of a high price.

Comparative ThreadLocalMap ThreadLocal core, as a storage container, the current thread key, value is a value, it retrieves the current value of the key corresponding to the thread or by a method to get the ThreadLocalMap

21, how to detect whether a thread has a lock?

java.lang.Thread there is a method holdsLock (Object obj), which returns true if and only if a specific object of the current thread owns the lock

22, how to obtain the thread stack in Java?

kill -3 [java pid]

  Current output will not be interrupted, it will output to the specified code execution or where to go. For example, kill -3 tomcat pid, output stack to the next log directory

Jstack [java pid]

  This is relatively simple, in the present display terminal, can also be redirected to the specified file.

JvisualVM

  Thread Dump, are open interface operation

23, JVM parameters on a thread

-Xss: stack size for each thread

24, what is the degree of concurrency ConcurrentHashMap?

ConcurrentHashMap the actual map is divided into several parts to achieve its scalability and security thread. This division is obtained by using the degree of concurrency, which is an optional parameter ConcurrentHashMap class constructor, the default value 16, so that multiple threads can avoid contention.

After JDK8, it abandoned the concept Segment (locking section), but a new way to enable the implementation, use CAS algorithm. While adding more auxiliary variables to improve concurrency.

25, what Semaphore in Java that?

Semaphore in Java is a new synchronization class, which is a count signal. Conceptually, a semaphore maintains a set of permissions. If necessary, block the permit is available each acquire (), and then get the license. Each release () adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects, only the number of licenses available Semaphore counts, and take the appropriate action. Semaphores are often used multi-threaded code, such as a database connection pool

26, the thread pool submit () and execute () method What is the difference

Both methods can be submitted to the thread pool tasks, execute method returns a value of void, which is defined in Executor interface.

submit method returns the calculation result held Future object, which is defined in ExecutorService interface, which extends Executor interface

27, what is blocking method?

It means the program will wait until the process is completed do not do other things during, ServerSocket's accept () method that has been waiting for client connections. Here is the obstruction before the call returns, the current thread is suspended, it will not return until after the results. In addition, asynchronous and non-blocking method returns before the task is completed

28, volatile variables and atomic variables What is the difference?

Volatile variables can ensure that first relationship, that is, the write operation will occur before a subsequent read operation, but it does not guarantee atomicity. For example, then count ++ atomic operations is not modified by volatile count variable.

Class provides the atomic AtomicInteger method may allow such operations are atomic as getAndIncrement () method will be atomic increment of the current value plus one, reference variables and other data types may be carried out similar operations.

29. What is your understanding of thread priority is?

Each thread has a priority, in general, high priority threads at runtime has priority, but this depends on the implementation of thread scheduling, and this implementation is operating system dependent (OS dependent). We can define the priority of the thread, but this does not guarantee high-priority thread will be executed before lower priority thread. Thread priority is an int variable (from 1-10), where 1 is the lowest priority and 10 is the highest priority.

java thread priority scheduling will be entrusted to the operating system to deal with, so with the specific operating system priorities related to, if not special needs, generally do not need to set thread priority.

30, how to ensure that main () method where the thread is the end of the last thread java program?

The main method is to allow other threads to wait for completion at the end, we can use the simplest join Thread class () method to ensure that all programs created by a thread before the end of main () method exits.

Second, you can use CountDownLatch, CyclicBarrier to block the main thread, etc.

31, how to communicate between threads?

wait object class (), notify (), notifyAll (), await (), signal (Condition interface), signalAll ()

32, synchronization method and synchronized block, which is the better choice?

Sync block, because he will not lock the entire object (of course, you can let him lock the entire object). Synchronization method will lock the entire object.

Sync block more in line with the principle of an open call, only to lock in the corresponding object code block needs to be locked, so that from the side to avoid deadlocks. Synchronization principle, the smaller the better, improve efficiency

33, how to create a daemon thread?

Use setDaemon Thread class (true) method can set a thread as a daemon thread, you need to pay attention to is the need to call this method before calling the start () method, otherwise it will throw an exception IllegalThreadStateException.

34, What is Java Timer class? How to create a task specific time interval?

java.util.Timer is a utility class that can be used to arrange a thread execution at a specific time in the future. Timer class can schedule one-time task or periodic task.

java.util.TimerTask regarded as a realization of the abstract class Runnable interface, we need to extend this class to create our own timing and use the Timer task to arrange it performs.

 35, "Ali Baba Development Manual" Why do you want to disable Executors way to create a thread pool?

Can refer to the thread pool -Executors: java concurrent programming analysis

Conclusion is:

Both FixedThreadPool and allowed SingleThreadExecutor Integer.MAX_VALUE request queue length, may accumulate a large number of requests, thereby causing abnormal OOM

CachedThreadPool number of threads created is allowed to Integer.MAX_VALUE, may create a large number of threads, causing abnormal OOM

So create a thread pool Alibaba development manual disable Executors of the way, the reason is recommended to create their own ThreadPoolExecutor

Reference: https://juejin.im/post/5dc41c165188257bad4d9e69

 

 

Guess you like

Origin www.cnblogs.com/xhy-shine/p/11316844.html