Java interview questions (4) - Multithreading

Java multi-threading, which has several ways.

implements Runnable, implements Callable,extends Thread


Callable and Future, understanding of FutureTask.
Callable and Future interfaces are under juc package.
Callable can perform asynchronous tasks, general and submit ExecutorService methods used together.
Future can monitor the task is completed, whether to cancel, cancel the job and get the result (blocking operation).
FutureTask:
implements Runnable and Future, so both the advantages of both.
You can either use ExecutorService, you can also use the Thread.
 

Callable and Future of understanding.

Callable and Future interfaces are under juc package.
Callable can perform asynchronous tasks, general and submit ExecutorService methods used together.
Future can monitor the task is completed, whether to cancel, cancel the job and get the result (blocking operation).
FutureTask:
implements Runnable and Future, so both the advantages of both.
You can either use ExecutorService, you can also use the Thread.

What are the parameters of the thread pool, to create a thread in the thread pool process.

The core argument:
workQueue: Before performing tasks for maintaining the queue.
keepAliveTime: the number of threads than the core number of threads, idle threads waiting for work overtime (in nanoseconds).
corePoolSize: remain active core minimum pool size
maximumPoolSize: maximum thread pool
to create ways:
newCachedThreadPool:
create a cache thread pool, thread pool longer than if treatment needs, the flexibility to reclaim idle thread, if not recyclable, the new thread.

newFixedThreadPool:
create a fixed-size thread pool, you can control the maximum number of concurrent threads, excess threads will wait in the queue.

newScheduledThreadPool: 
create a fixed-length 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 to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

newWorkStealingPool:
the JDK 1.8 after the new out, in order to prevent excessive thread pool enabled, cpu usage excessive downtime caused by the project. Adapted to perform multiple tasks and each task takes less time. 4 ways above are likely to occupy high cpu happens.

Creation process:
1, to determine the core thread pool threads are all on a mission, if not (core thread is idle or there is no core thread is created) is working to create a new thread to execute the task. If the core threads are on a mission, then enter the next process.

2, the thread pool to determine whether the work queue is full, if the work queue is not full, the task will be stored in the newly submitted job queue. If the work queue is full, then enter the next process.

3, to determine whether the thread pool threads are in working condition, if not, create a new worker thread to perform the task. If full, then to the saturation strategy to deal with this task.

Volitile key role, principles.

Ensure visibility of memory:
Memory Visibility (Memory Visibility): all threads can see the latest status of shared memory.
Before each reading must start with the main memory refresh date value.
After each write must be synchronized back to the main memory of them immediately.
Preventing reordering instructions:
volatile keyword to prevent the instructions are reordered by "memory barrier."
In order to achieve volatile memory semantics, the compiler when generating bytecode will be inserted in the instruction sequence memory barrier to inhibit a particular type of processor reordering.
(Lazy loading case is a case of a single embodiment mode, the instruction memory model Happens-Before rearrangement produces two objects)
can not guarantee atomicity:
This variable is limited to the atom (including a reference) to read and write, can not cover any operations on the variables (e.g., count ++)

https://www.cnblogs.com/monkeysayhi/p/7654460.html

Use of synchronized keyword, advantages and disadvantages.

Usage:
the method, process, block, depending on the object lock.
Advantages:
ensure synchronization relationship between the thread that is.
Synchronized innate exclusive, reentrancy.
jdk1.6 after the lock has been optimized for synchronized, it contains biased lock, lock lightweight, heavyweight lock.
Cons:
No way to set the waiting time to acquire the lock may result in a blocked state indefinitely.
For applications reading and writing less it is very negative, because even more readers seemingly can run concurrently, but they actually still serial, and will eventually lead to a decline of concurrent performance.

https://www.jianshu.com/p/d53bf830fa09

Lock interface to achieve what class, what use scenarios Yes.

Implementation class of ReentrantLock, meaning "reentrant lock", the operation may be interrupted acquire the lock, the lock acquisition timeout time can be set.
Implement the interface ReadWriteLock. Read-write locks allow multiple threads execute concurrently, but does not allow write and read threads concurrently executing threads, thread is not allowed to write and write concurrently executing threads.
ReentrantReadWriteLock implemented in ReadWriteLock, read and write the same time allowed access by multiple threads read, but write access to the thread, all threads read and write other threads are blocked.

Fairness options: support non fairness (default) lock acquisition and equitable way, throughput is better than fair or unfair;
reentrant: can get support once again re-entry, after reading lock acquisition can get again, after a write lock acquisition write locks, but also to acquire a read lock;
lock downgrade: follow obtain a write lock, then release order to obtain a read lock to write lock, write lock to be able to demote a read lock.

https://www.jianshu.com/p/4a624281235e

Comparative synchronized and the lock.

lock allows other threads try to obtain a lock just waiting for some time. The synchronized modification of the code block executed, in order to release the lock. Or thread of execution exception occurs, JVM will automatically thread releases the lock.
Read and write, write and write conflicts will happen, but read and read operations do not conflict, Lock you can allow this operation can be carried out simultaneously. (Read-write lock)
Lock can not know the thread has successfully acquired the lock.
When resources are very fierce competition, Lock's performance will be better. (Specific scenario analysis)
sychronized is not interrupted Lock, Lock interruptible. (Interruptible lock)
Lock fair lock may be provided, according to the order of the dispensing lock the lock request. (Fair lock)
can condition variables and with the use of multiple states to monitor the shared data.

https://blog.csdn.net/weixin_40255793/article/details/80786249

 

Reentrant lock usefulness and implementation principle, the process of copy-write, read-write locks, lock segment (segment ConcurrentHashMap in).

Definition:
If a program or subroutine may "at any time is interrupted and the operating system scheduled for execution another section of code, which in turn calls the subroutine can not go wrong,"
claimed it as reentrant (reentrant or re- entrant) of. That is when the subroutine is running, a thread of execution can re-enter and execute it, and
still get the results in line with expectations at design time. And concurrent execution of multiple threads of different thread-safe, reentrant emphasis on re-entering the same routine execution of a single thread is still safe.
Principle:
Each holder of a lock associated with a thread and a counter when the counter is 0 indicates that the lock is not held by any thread, any thread may acquire the lock and call the appropriate methods;
When a thread requests successfully , the JVM will remember thread holds the lock, and the counter is set to 1; another thread requests the lock case, it must wait;
and the thread holding the lock request if the lock again, the lock can again get and the counter is incremented;
when a thread exits sync block, the counter is decremented, if the counter is 0, the lock is released.
Scene:
When reentrant lock primarily require multiple threads to enter the critical area code, requires the use of reentrant lock.
When a specific example, such a synchronized method mentioned above it requires a synchronized method call another.
Write lock:
write lock custom dependency synchronizer isochronous functions, i.e. read-write synchronization state synchronizer. The write lock variable shaping cut into two parts, the upper 16 bits represent read, write the lower 16 bits represent.
Calculate respective read-write lock synchronization status bit operation.
Suppose the current synchronization state is c, it is a write state c & 0x0000FFFF, read state c >>> 16 (0 complement bit unsigned 16-bit right shift).
When the write state to a state of increased c + 1, when an increase in the read state, the status code is c + (1 <<< 16).
Acquiring a read lock:
ThreadLocal thread local objects, will save many times each thread acquires the lock to the inside of each thread, so that when the lock release will not affect other threads. 
tryAcquireShared use fullTryAcquireShared cas after the failure to obtain a lock.
First read-write lock state for all threads acquire the number of read locks, as is the reentrant lock, and because the number of read locks to preserve each lock acquired by the local variables for each lock thereby increasing the reading target ThreadLocal the difficulty of the process of obtaining,
prior to each acquire a read lock to determine whether there will be a exclusive write locks, exclusive write locks if there is failure to obtain direct return into the synchronous queue.
If no write lock is acquired, the thread may obtain a read lock, due to the presence of shared locks, each will get the type judgment threads, each thread in order to acquire synchronization state when they are self-increasing in its corresponding local variables operating.
Acquire write lock:
obtain a write lock compared to acquire a read lock on a lot simpler, before acquiring a read lock only need to determine whether there is currently a read lock, so if there is a read lock acquisition fails,
which can then determine whether to obtain a write lock for the current thread If the thread is not a failure otherwise re-entry locks on the increase since the existing state value.
Read-Write Lock downgrade:
lock is downgraded downgrading from the write lock to be read locks. The case has a write lock in the current thread, once again to get a read lock, write lock process lock is then released downgrade.
Lock segment:
JDK. 8 before, ConcurrentHashMap lock segment HashTable exclusive lock in place. Segment of ReentrantLock inherited reentrant lock, with lock function, while the plus chain-like structure comprising an array of HashMap.
jdk has been abandoned after 8 segments locked because of the following:
adding a plurality of segments lock wasted memory space.
Production environment, map when placed in competition with a lock probability is very small, but the segment lock can cause long waits for updates and other operations.
In order to improve the efficiency of the GC.

https://www.cnblogs.com/wait-pigblog/p/9350569.html


Pessimistic locking, optimistic locking, advantages and disadvantages, CAS have any defects, what is the solution.

Optimistic lock:
it that reading and writing less and less concurrent modification, others will not be modified each time to get the data, so it will not be locked.
Update time will check what this data has not been updated. Specific strategies is to get the current version before the update,
and then compare the version number and the last, and then update the same, and if that fails will have to repeat read - Compare - write operation.
Use: Lock in the framework of AQS is the first attempt to acquire cas optimistic locking lock, get less, will be converted to a pessimistic lock, such as RetreenLock.
Pessimistic locking:
pessimistic locking it that write more, and more concurrent modification, each time to get the data will be locked, others will want to read and write data until the block to get the lock.
Use: synchronized
CAS advantages:
non-blocking lightweight optimistic locking, by CPU instructions, and high in the resource less competitive situation performance,
compared to the weight of synchronized locks, synchronized will be more complex lock, unlock and wake operating.
CAS disadvantages: 
1. ABA problem. Before is updated version A, is updated by the intermediate A-> B-> A, this time to get the threads that have not been updated.
java classes atoms AtomicStampedReference, the version number of the control variable value to ensure the correctness of CAS.
DETAILED Solutions version number is added in front of the variables, each variable is updated when the version number or timestamp plus one,
then A - B - A becomes. 1A - 2B -. 3A
2. spin time is too long, consume CPU resources, if resources are highly competitive, multi-threaded spin-long consumption of resources.

https://blog.csdn.net/qq_20499001/article/details/90315061


Unfair lock, the difference between fair locks.


Multi-threaded execution order of latitude lock will lock into equity and non-equity locks.
Fair locks: lock before waiting to see if there is a thread, the thread top surface of any priority, first come first served.
Unfair lock: once CAS direct attempt to acquire the lock when locked, if no response is received,
then judge once (tryAcquire method if the lock is free, direct access) did not get to go the tail queue.
ReentrantLock supports two locks.
ReentrantLock fair tryAcquire method Notes:
.. Fair tryAcquire Version of the Do not Call or Grant Access The unless recursive This IS NO First Waiters or
fair version of tryAcquire. Unless it is called recursively or no waiters, otherwise not allowed to access.
Unfair tryAcquire method Notes:
. Performs nonfair tryLock tryAcquire IS Implemented The in subclasses, But both-need nonfair tryLock Method, for the try.
Execution of non-equity tryLock. tryAcquire is implemented in the subclass, but both unfair methods to try trylock needs.
The difference is that tryAcquire determined state = 0 (reference lock 0), non-equity direct call CAS, and fair locks to ensure that no thread before the current thread, and can only be CAS.
Use:
more direct use of non fair lock; unfair lock lock 5-10 times higher than fair performance, because the need to maintain fairness lock a queue in case of a multi-core,
If the current thread is not the first queue can not get a lock, an increase of thread switching times.

https://www.jianshu.com/p/2ada27eee90b
http://www.cnblogs.com/darrenqiao/p/9211178.html


Biased locking distinction lightweight lock, spin locks, heavyweight lock.


Spin lock:
If you hold a lock resources in a very short period of time can release the lock, other threads do not need to enter the blocked state, just wait a minute (spin),
and other thread releases the lock after lock acquisition immediately. This avoids consuming switching between user and kernel threads.
Spin is the need to consume the cpu, you need to set the spin time, over time thread enters blocked.
Advantages:
reduction thread is blocked, the lock for the next competition is not fierce, holding the lock time is very short, performance has improved so much, spin
the cpu consumption is smaller than the thread blocked and then wake up (thread context switching occurs twice)
Disadvantages:
If multi-thread compete for resources, and the thread that holds the lock for a long time, then, spin-wait cpu consumption should be
greater than the thread blocks consume wake up again, resulting in a waste of cpu.
Spin lock time setting threshold:
the JDK 1.6 after the introduction of adaptive spin lock spin time is not a fixed,
but by the same previous spin lock time, and the lock owner of state to decide.
The basic thought a thread context switch time is the best time.
JVM optimization:
if the average load <number of cpu, the spin has been
exceeding the number of cpu / 2 threads are spinning, then later blocked thread directly
if you are found Owner spin thread changes the spin delay time ( the spin-count) or into the blocked
if the CPU is in the power saving mode stops the spin
spin worst case time delay stored in the CPU (CPU a stores a data, that the time difference to CPU B of this data directly)
the spin will be appropriate to give up the difference between the thread priority when
after JDK7 spin control parameters by the JVM

Biased locking:
lock flag 01
tend to lock, as the name suggests, it will tend to first access the lock thread,
if during operation, only one thread synchronization lock access, plus it will give a biased locking thread, you do not need to visit again CAS. If during operation, met with other threads to seize the lock, biased locking thread that holds will be suspended, JVM will eliminate its body biased lock, the lock reverts to the standard lightweight lock.
Process:
Mark Word of biased locking identified as 01, is biased lock.
If the state is biased, more access points to the thread ID of the current thread.
If so, direct synchronization, if not, checks the ID point to a thread is alive.
If you hang up, the new thread is holding a lock bias, otherwise, the upgrade is a lightweight lock (CAS replace Mark Word failed).
Biased locking will first withdraw and then upgrade, will lead to revocation of STW.

Lightweight lock:
Lock flag 00
lightweight lock is biased by the upgrade to the lock.
It refers to obtain two threads alternately acquire the lock thread or another spin lock time threshold, which is lightweight lock.
At this point Mark Word points to the current thread's stack frame.
If the time exceeds the threshold leads to another thread into the blocked, lightweight lock is released upgraded to heavyweight lock.

Heavyweight lock:
Lock flag 10
heavyweight lock was upgraded from a lightweight lock come.
Multiple threads competing for the same lock.
At this point Mark Word points to hold heavyweight lock thread's stack frame.
Heavyweight locks Synchronized:
the JVM takes out data from the end of the queue for a lock contention candidate (OnDeck), but the concurrency, ContentionList CAS is accessed for a large number of concurrent threads, in order to reduce competition for the tail element, the JVM It will be moved to a portion of the thread as a candidate competing EntryList thread. Owner threads in the unlock, the ContentionList in part thread migration to EntryList and specify a thread in EntryList is OnDeck thread (usually the first to go in that thread). Owner thread does not pass directly to OnDeck thread lock, but the lock contention right handed OnDeck, OnDeck need to re-lock contention. Although this sacrifices some fairness, but can greatly enhance the throughput of the system, in the JVM, but also to choose this behavior as "competitive switch."
OnDeck thread to acquire the lock after resource becomes Owner threads, but did not get a lock resource still stuck in EntryList in. If the thread is blocked Owner wait method, then transferred to WaitSet queue until a certain moment by notify or notifyAll wakes up, will go again in EntryList.
Synchronized non-fair locks. Synchronized in the thread enters ContentionList, waiting threads will attempt to acquire the lock spin, if you can not get into the ContentionList, which for obvious thread has entered the queue is not fair, there is an unfair thing is to get the spin lock thread may also direct resources to seize the lock OnDeck thread.
ContentionList ——> EntryList ——> OnDeck ——> Owner ——> WaitSet ——> EntryList(wait后notify回到EntryList)

https://blog.csdn.net/zqz_zqz/article/details/70233767
https://blog.csdn.net/tian251yu/article/details/80638104

 

How to ABC three threads to ensure the execution order.


Fair way lock:
of ReentrantLock of ReentrantLock Lock new new = (to true);
Lock.lock ();
BlockingQueue manner:
a LinkedBlockingQueue new new = a LinkedBlockingQueue Queue ();
queue.put ();
queue.poll ();


What are the state of the thread.


New (New): created a new thread object.
Ready (Runnable): After the thread is created, call the start method. The thread is present in "runnable thread pool", only waiting for the right to use the cpu.
Running (Running): get ready thread cpu, run.
Blocked (Blocked): running thread for some reason (call the wait method) to give up the right to use cpu, pauses,
until the thread wakes up into the ready state (call to notify method), have a chance to run.


https://www.cnblogs.com/jijijiefang/articles/7222955.html

The difference between sleep and wait.


sleep is a Thread class method, wait method is the Object class.
sleep did not release the lock, wait method releases the lock, the wait thread re-enter the blocked thread pool
until the other thread calls notify / notifyAll enter the ready state.
sleep (milliseconds) can be specified time so it automatically wake up, can only be called if less than interrupt () forcibly interrupted.
Role Thread.Sleep (0) is "operating system immediately triggers a re-CPU competition."

https://www.cnblogs.com/plmnko/archive/2010/10/15/1851854.html


The difference notify and notifyall.

The key difference between notify and notifyAll that notify () will only wake a thread, notifyAll method will awaken all threads.
In fact, every object has two pools, pool are waiting for the lock pool (EntrySet) and (WaitSet).

Lock pool: If have A thread acquired the lock, this time another thread B needs to acquire the lock (such as the need to call synchronized modification method or a need to perform synchronized modified code blocks), since the lock is already occupied, so the thread B can only wait for the lock, this time thread B will enter the lock lock pool.
Wait Pool: A thread is assumed that after the lock is acquired, does not satisfy a number of conditions (e.g., Producer Consumer Producer acquired lock mode, and determines the queue is full), then call wait method requires the object lock, the thread a will give up the lock and enter the lock of the pool waiting.
If there are other thread calls the notify method locks will select a thread from the wait pool according to certain algorithms, lock this thread into the pool.
If there are other thread calls notifyAll method lock, it will be waiting for all threads in the pool all pool into the lock, and lock competition.
Difference lock pool and pool waiting: waiting pool thread can not acquire the lock, but the lock needs to be awakened into the pool, have the opportunity to acquire the lock.

https://blog.csdn.net/liuzhixiong_521/article/details/86677057


ThreadLocal understanding, implementation principle.

ThreadLocal provide a thread (Thread) local variable, each thread to access a variable has its own local variables.
Thread each object has a ThreadLocalMap, when creating a ThreadLocal and they will add the ThreadLocal objects to the Map, where the key is ThreadLocal, value can be any type.

https://www.jianshu.com/p/ee8c9dccc953

Published 115 original articles · won praise 58 · Views 230,000 +

Guess you like

Origin blog.csdn.net/Angry_Mills/article/details/82107312