Knowledge finishing point, Java concurrent programming interview questions (b)

EDITORIAL

Compiled some Internet giant face questions, questions often asked these surfaces, as Java engineer also need to have some knowledge, after all, the combination of theory and practice, is king, fragmentation finishing, nibbling some knowledge every day , happy every day, if you have help, remember that the point of a concern and a point like oh .

Related series

Knowledge finishing, MyBatis face questions
knowledge consolidation, ZooKeeper face questions
knowledge consolidation, Dubbo face questions
knowledge consolidation, Elasticsearch face questions
knowledge consolidation, Redis face questions
knowledge consolidation, MySQL face questions
knowledge consolidation, Java concurrent programming interview title (a)
knowledge consolidation, Java concurrent programming interview questions (b)

Concurrent programming three elements?

  • Atomicity Atomicity refers to one or more operations, and performing either all other operations will not be interrupted during execution, or to all without execution.
  • Visibility Visibility refers to a plurality of threads operating shared variable, wherein the variable modify a thread, other threads can immediately see the results of changes.
  • Ordering orderly, i.e., program execution sequence performed in the order code.

Way to achieve visibility of what?

synchronized or Lock: to ensure that only one thread at the same time acquire the lock code execution, before the release of the latest value of the lock flushed to main memory, to achieve visibility.

The value of multi-threaded?

  • Play the advantages of multi-core CPU multithreading, you can really play the advantages of multi-core CPU to achieve the purpose of full use of CPU, multi-threaded approach to the completion of several things simultaneously without interfering with each other.
  • Prevent obstruction from the point of view of efficiency program, not only single-core CPU multithreading will not play advantage, because it will run on a single core CPU multithreading lead to thread context switches, and reduce overall program efficiency. But we still have to single-core CPU multi-threaded applications, it is to prevent clogging. Just think, if it is before the single-core CPU using a single thread, so as long as this thread is blocked, say a data remotely read it, the peer has not yet been returned and no set time-out, then your entire program in return data back stopped working. Multithreading can prevent this problem, a number of threads to run simultaneously, even if a code execution thread to read data blocked, it will not affect the execution of other tasks.
  • This ease of modeling is another not so obvious advantages of. Suppose you have a large task A, single-threaded programming, then you must consider a lot, build the entire program model is too much trouble. But if this great task A broken down into several small tasks, task B, task C, task D, were established program model and run these tasks through multi-threading, respectively, then a lot simpler.

What are the ways to create a thread?

  • Thread class inheritance Thread class is created
  • Create threads through the Runnable interface class
  • Create a thread through Callable and Future
  • Created by a thread pool

Comparison of three ways to create a thread?

  • Adopted to achieve Runnable, Callable way to create multi-threaded interface

Advantages are : thread class only implements the interface Runnable or Callable interface, you can also inherit from other classes. In this way, multiple threads may share the same target object, is the same for a plurality of threads to deal with a case where the same resources, which can be separated to form a clear model of the CPU, code and data, to better reflect the object-oriented thinking.
Disadvantages are : programming a little more complicated, if you want to access the current thread, you must use the Thread.currentThread()method.

  • Create multi-threaded use the Thread class inheritance

Advantages are : to write simple, if you need access to the current thread, you do not need to use Thread.currentThread () method, the direct use this to get the current thread.
Disadvantages are : Thread class Thread class has been inherited, so can not inherit other parent.

  • The difference Runnable and Callable
    • Callable predetermined (override) is a method call (), Runnable predetermined (override) method is run ().
    • Callable tasks can be executed after the return value, and Runnable task is not the return value.
    • Call method may throw an exception, run method can not.
    • Run Callable task can get a Future object that represents the result of an asynchronous computation. It provides a method of checking computation is complete, to wait for the completion of calculation, and calculation of the search result. By Future object can understand the implementation of the mandate, to cancel the execution of the task, but also get the results.

Fifth Java thread has a basic state

  • New state (New) : When the thread object after creation, that is, into the new state, such as:Thread t = new MyThread();
  • Ready state (Runnable) : When the start () method (the calling thread object t.start();), the thread that is ready state. Thread in the ready state, is illustrative of this thread is ready, waiting for the CPU scheduled for execution at any time, not to say that the implementation of the t.start () This thread will be executed immediately;
  • Running state (Running) : When the CPU thread scheduling is started in a ready state, and this time was able to really execute threads that go into run mode. Note: ready state is the only means of access to the operating state, that is, the thread execution in order to enter the running state, first of all must be in a state of readiness;
  • Blocked (Blocked) : running the thread for some reason, temporarily give up the right to use the CPU, stop the execution, this time into the block until it enters the ready state, have a chance to enter the CPU is called again to an operational state.

Depending on the reason for blocking generated, blocked state can be divided into three kinds :

  • Wait blocking : a thread of execution running state wait () method, so that the thread enters the wait state obstruction;
  • Synchronous blocking : get synchronized thread synchronization lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state;
  • Other blocking : The sleep () or join the calling thread () or issued I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
  • Death state (Dead) : thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

What is the thread pool? What are the different ways to create?

Advance the thread pool is to create several threads, if there is need to deal with the task, the thread pool thread will handle the task, after processing threads and will not be destroyed, but waiting for the next task. Because creating and destroying threads are consuming system resources, so when you want to frequent creating and destroying threads can consider using the thread pool to improve system performance. java provides an java.util.concurrent.Executorimplementation of the interface used to create a thread pool.

Creating Four thread pool

  • newCachedThreadPool create a thread pool cacheable
  • newFixedThreadPool create a fixed-size thread pool, you can control the maximum number of concurrent threads.
  • newScheduledThreadPool create a fixed-size thread pool to support regular and periodic task execution.
  • newSingleThreadExecutor create a single-threaded thread pool, use it only to perform the task only worker threads.

Thread pool advantage?

  • Reuse existing threads, reducing the overhead of object creation destroyed.
  • Can effectively control the maximum number of concurrent threads, improve utilization of system resources, while avoiding excessive competition for resources, to avoid clogging.
  • It provides timing executed to perform regular, single-threaded, concurrent control.

Common concurrency tools What?

  • CountDownLatch
  • CyclicBarrier
  • Semaphore
  • Exchanger

CyclicBarrier and the difference CountDownLatch

  • CountDownLatch simply means that a thread to wait until another thread is waiting for his execution were completed and calls countDown () method to be notified when the current thread can continue execution.
  • cyclicBarrier all threads waits until all threads are ready to enter the await () method after all threads started!
  • CountDownLatch counter can only be used once. The counter can be used CyclicBarrier reset () method to reset. So CyclicBarrier can handle more complex business scenarios, such as if calculation error occurs, you can reset the counter, and let the threads are executed once again.
  • 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. Returns true if interrupted, otherwise false.

synchronized action?

In Java, synchronized keyword is used to control the thread synchronization, that is, in a multithreaded environment, the control code segments are not synchronized simultaneous execution of multiple threads. synchronized either added to the piece of code may be added to the method.

The role of the volatile keyword

For visibility, Java provides the volatile keyword to ensure visibility. When a shared variable is declared volatile, it will ensure that the modified values ​​will be updated immediately to the main memory, when there are other threads need to read, it will read the new value to memory. From a practical point of view, an important role is volatile and CAS combined to ensure the atomicity, details can be found under the category java.util.concurrent.atomic package, such AtomicInteger.

What is CAS

CAS is an abbreviation compare and swap, that is what we call comparative exchange. cas is a lock-based operation, and is optimistic locking. In java lock into optimistic and pessimistic locking. Pessimistic lock is locked resource, such as after a thread releases the lock before obtaining the lock, the next thread can access. The optimistic locking taking a broad approach to processing resources by not locking in some way, such as to obtain the data by adding to the record version, a more pessimistic locking performance has greatly improved.

CAS operation includes three operands - a memory location (V), is expected to original value (A) and the new value (B). If the value of the memory address and the value of A which is the same, then the values will be updated to the memory inside B. CAS is to get the data through an infinite loop, Ruoguo cycle in the first round, a thread gets inside the address value is modified b-threaded, then a thread needs to spin cycle to the next possible opportunity to perform. java.util.concurrent.atomicMost packages under the CAS operation class is implemented ( AtomicInteger,AtomicBoolean,AtomicLong).

CAS issues

  • CAS is likely to cause a problem ABA
    thread a numerical value into a b, and then they changed it to a, CAS considered at this time has not changed, in fact, has changed too, and the solution to this problem you can use the version number to identify each plus a version 1 operation. In java5 it has been provided AtomicStampedReference to solve the problem.
  • Code blocks can not be guaranteed atomicity of
    atomic operations to ensure knowledge CAS mechanism of a variable, and can not guarantee the atoms of the entire code block. Such as the need to ensure that three variables common to update atomicity, you have to use a synchronized.
  • CAS cause an increase in CPU utilization
    said the process of CAS there is a cycle before the judge, if the thread has not acquired status, cpu resources will always be occupied.

What is the Future?

In concurrent programming, we often use non-blocking model, to achieve the three previous multi-threaded, whether inherited or implement thread class runnable interfaces, they can not guarantee the implementation of previous results obtained. By implementing Callback interface and can be received by the multi-threaded execution result Future. Future represents the result may not have a complete asynchronous tasks for this result can be added Callback in order to make the appropriate action after the task execution success or failure.

What is the AQS

AQS is AbustactQueuedSynchronizershort, it is a Java-based tools to improve the level synchronization, the synchronization state represented by a variable of type int, and provides a series of CAS operations to manage the synchronized state. AQS is used to build a frame lock and a synchronizer, using AQS can be constructed simply and efficiently a large number of widely synchronizer, such as we mentioned ReentrantLock, Semaphore, other such ReentrantReadWriteLock,SynchronousQueue,FutureTasklike are all based on the AQS.

AQS supports both synchronous mode

  • Exclusive formula
  • Shared

Such user-friendly implement different types of synchronization component of ReentrantLock as exclusive, shared, such as Semaphore, CountDownLatch, such as modular ReentrantReadWriteLock. In short, AQS provides underlying support for the use, how to assemble achieve, users can play for free.

What is ReadWriteLock

First clear look at, not to say ReentrantLock bad, just ReentrantLock sometimes have limitations. If you use ReentrantLock, may itself be in order to prevent the thread A write data, data inconsistencies thread B in the read data caused, but this way, if the thread C in reading data, the thread D also read data, the read data will not change the data, it is not necessary lock, but still locked up, reducing the performance of the program. Because of this, before the birth of the read-write lock ReadWriteLock. ReadWriteLock interfaces is a read-write lock, is a specific implementation ReentrantReadWriteLock with ReadWriteLock interface, realizes the separation of read and write, a read lock is shared, exclusive write lock is not mutually exclusive write and read, read and write, will mutually exclusive between the write and read, write, and write, read and write performance improves.

What is FutureTask

This fact has mentioned earlier, FutureTask indicates that the task of an asynchronous operation. FutureTask which can pass a Callable implementation class may be made to wait for access to the results of the task asynchronous operations, has been completed is determined whether to cancel the operation tasks. Of course, since FutureTask also Runnable interface implementation class, so FutureTask also can be placed in the thread pool.

The difference between synchronized and ReentrantLock

synchronized and is if、else、for、whilethe same keyword, ReentrantLock is class, which is the essential difference between the two. Since ReentrantLock is a class, then it provides more flexibility than the synchronized characteristics can be inherited, there are ways you can, you can have a variety of class variables, scalability synchronized ReentrantLock than reflected in the points:

  • ReentrantLock can be set to acquire the lock wait time, thus avoiding deadlock
  • ReentrantLock can obtain information on the various locks
  • ReentrantLock the flexibility to implement multi-channel notification In addition, both the lock mechanism is actually not the same. ReentrantLock low-level calls that park Unsafe methods of locking, synchronized operation should be the subject header mark word, which I can not determine.

What is the optimistic and pessimistic locking

Optimistic locking: As its name suggests, for thread safety issues between concurrent operations generated optimistic state, optimistic locking that competition does not always happen, so it does not need to hold the lock, the comparison - replace these two actions as an atomic operation attempts to modify variables in memory, if said conflict fails, then there should be a corresponding retry logic.

Pessimistic lock: or, as its name suggests, for thread safety issues between concurrent operations generated a pessimistic state, pessimistic locking that competition will always happen, so every time a resource operation, will hold an exclusive lock, like synchronized, willy-nilly, operating directly on the lock on the resource.

Thread A Thread B know how to modify the variables

  • volatile modifying variables
  • synchronized modification method modify variables
  • wait/notify
  • while polling

synchronized, volatile, CAS compare

  • synchronized pessimistic locks, are preemptive, other threads will cause clogging.
  • volatile multi-threaded shared variables provide visibility and prohibit instruction reordering optimization.
  • CAS is based on optimistic locking conflict detection (non-blocking)

sleep method and wait method What is the difference?

This question is often asked, sleep and wait method method can be used to give up some CPU time, except that if the thread holding an object monitor, sleep method does not give up this object's monitor, wait method will give up this object monitor

What ThreadLocal that? What is the use?

ThreadLocal thread is a local copy of the variable tools. Mainly for the private copy of the object stored in the thread and the thread to do a mapping, variable between individual threads without disturbing each other, in a highly concurrent scenarios can be achieved without state calls, especially for dependent variable values each thread does not make sense complete scenes operations. Simply put ThreadLocal is a kind of space for time approach, in which each Thread to maintain an open address method implementation ThreadLocal.ThreadLocalMap, data isolation, data is not shared, naturally, there is no question of the security thread.

Why wait () method, and notify () / notifyAll () method to be invoked in the sync blocks

This JDK is mandatory, wait () method, and notify () / notifyAll () method must first obtain the object before calling lock

Multi-thread synchronization, which has several methods?

Synchronized keyword, Lock locks for distributed lock.

Thread scheduling policy

Thread scheduler selects the highest priority thread to run, however, if the following occurs, it will terminate the thread running:

  • Thread body called yield ways to get out of the right to occupy the cpu
  • Thread body called sleep method enables the thread to sleep
  • IO operation is blocked because the thread
  • In addition a higher priority thread appears
  • In the system supports time slice, the thread's time slice runs out

What is the degree of concurrency ConcurrentHashMap

ConcurrentHashMap concurrency is the size of the segment, the default is 16, which means that there can be up to 16 threads simultaneously operating ConcurrentHashMap, which is the biggest advantage of the Hashtable ConcurrentHashMap, in any case, there are two threads simultaneously Hashtable can get the Hashtable data?

How to Find Linux environment which thread uses the CPU longest

  • pid acquisition projects, jps or ps -ef | grep java, have talked about this in front
  • top -H -p pid, the order can not be changed

Java deadlocks and how to avoid?

Java is a programming in a deadlock situation in which two or more threads are permanently blocked, Java deadlock situation at least two threads and two or more resources. Java root cause of deadlock are: Cross occurred when applying for a closed-loop application lock.

Cause of a deadlock

  • Multiple threads involves multiple locks, these locks there is cross, it could lead to a dependence lock loop .
    For example: in the case of threads get locked down A and did not release the application lock B, then, it has gained another thread lock B, and B before releasing the lock must first obtain a lock A, and therefore closed loop occurs, the deadlock cycle .
  • The default lock application operation is blocked .
    So to avoid deadlock, it is necessary in the case of a face lock multiple objects intersect, we must carefully examine all the methods in the class of these objects, whether there is a possibility lead to dependence lock loop. All in all, try to avoid other objects and methods delay synchronization method calls in a synchronous approach.

How awaken a blocked thread

If the thread is blocked because the call wait (), sleep () or join () method caused, can interrupt threads, and to wake it up by throwing InterruptedException; if the IO thread encounters a blockage, do nothing, because the operating system IO implementation, Java code and no way to directly access to the operating system.

Immutable objects are going to help multithreading

There is a problem mentioned in the foregoing, the immutable object to ensure visibility of memory objects, to read immutable object does not require additional synchronization means to enhance the efficiency of code execution.

What is multi-threaded context switch

Multi-thread context switch refers to the control of the CPU switch from an already running thread to another place and wait for the process of obtaining execution of the CPU threads.

If you submit the task, the thread pool queue is full, then what will happen

Here we distinguish between:

  • If you are using LinkedBlockingQueue unbounded queue, the queue is unbounded, then it does not matter, continue to add tasks to the blocking queue waiting to be executed, because LinkedBlockingQueue can be considered almost an infinite queue, you can store unlimited tasks
  • If it is bounded queue used such ArrayBlockingQueue, the first task will be added to the ArrayBlockingQueue, ArrayBlockingQueue full, will increase the number of threads maximumPoolSize value, if increasing the number of threads or handle, however, continue ArrayBlockingQueue full, it will be used RejectedExecutionHandler processing tasks rejection policy is full, the default is AbortPolicy

What Java thread scheduling algorithm is used

Preemptive. After a thread run out of CPU, operating system will be calculated based on a total priority thread priority, thread starvation situation and other data and assign the next time slice to execute a thread.

What is the thread scheduler (Thread Scheduler) and time slicing (TimeSlicing)?

Thread scheduler is an operating system service, which is responsible for the state of Runnable thread allocation of CPU time. Once we create a thread and start it, it will depend on the implementation of the implementation of the thread scheduler. Refers to the process time slice is the available CPU time assigned to an available thread Runnable. Allocates CPU time can thread priority or thread wait on. Thread scheduling is not controlled by the Java virtual machine, so the application to control it is a better choice (that is to say do not let your application depends on the priority of the thread).

What is Spin

Many synchronized code inside just some very simple code, very fast execution time, then wait for the thread lock might be a less worthy of operation, because the thread blocking issues related to the user mode and kernel mode switching. Since the code execution inside the synchronized very fast, let's wait for the lock thread is not blocked, but do busy circulating in the border synchronized, this is spin. If you do not find that many times get busy cycle lock, and then blocked, this may be a better strategy.

What JavaConcurrencyAPI the Lock Interface (Lockinterface) yes? Contrast synchronization is there any advantage?

Lock Interface sync blocks than the synchronization method and provide lock operation more scalable. They allow a more flexible structure, may have completely different properties, and may support a plurality of conditions related to the object classes. Its advantages are:

  • You can lock fairer
  • The thread can interrupt response time of waiting for the lock
  • It allows thread tries to acquire the lock 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

Thread safety Singleton pattern

Commonplace problem, the first thing to say is thread-safe means Singleton pattern: an instance of a class will only be created once out in a multithreaded environment. There are many cases of single mode of writing, I summarize:

  • Writing hungry man single-mode example: Thread safety
  • Lazy writing style Singleton pattern: non-thread-safe
  • Double lock detection wording singletons: Security Thread

What is the role Semaphore

Semaphore is a semaphore, its role is to limit the number of concurrent certain code block. Semaphore has a constructor, you may pass an int type integer n, represents a piece of code at most n threads can access, if exceeded n, then please wait until a thread completes this code block, the next thread re-entry. It can be seen that if the incoming Semaphore constructor type integer int n = 1, the equivalent into a synchronized.

What Executors class is?

Executors provides tools method Executor, ExecutorService, ScheduledExecutorService, ThreadFactory and Callable classes. Executors can be used to easily create a thread pool

Thread class constructor, is called a static block which thread

This is a very tricky and tricky questions. Remember: Thread class constructor, static block is where the new thread is the thread class called, and run the code inside the method is being called by the thread itself. If the above statement makes you feel confused, then I give an example, suppose Thread2 in new a Thread1, main function in new the Thread2, then: 1, Thread2 construction methods, static block is a main thread calls, Thread2 the run () constructor method 2, the Thread1 Thread2 their call, the static blocks are called Thread2, Thread1 the run () method is invoked their Thread1

Synchronization method and synchronized block, which is the better choice?

Sync blocks, which means that code outside the sync block is asynchronous, which further enhance the efficiency of the overall process than synchronous code. Please know that a principle: when synchronization as possible.

Java thread count too much can cause anything unusual?

  • Life cycle cost is very high thread
  • Consume excessive CPU resources if the number of threads that can run more than the number of available processors, then there will be idle threads. A large number of idle threads will take up a lot of memory, to bring pressure on the garbage collector, and a large number of threads will incur the overhead of other performance when competing for CPU resources.
  • Stability of the presence of a reducing JVM limited in number of threads can be created, this limit will vary with the platform and receiving a plurality of factors, including the size of the JVM startup parameter request stack of the Thread constructor, and restrictions on the underlying operating system thread and so on. If the destruction of these restrictions, you may throw an OutOfMemoryError.
Published 122 original articles · won praise 591 · Views 1.08 million +

Guess you like

Origin blog.csdn.net/DBC_121/article/details/104823383