Concurrent multi-threaded Java

1. Why use a thread pool

Avoid frequent create and destroy threads, to reuse the thread object. In addition, using a thread pool can also be flexibly controlled according to the number of concurrent projects.

 

2.java how to get to the thread dump file

Infinite loop, deadlocks, blocking, the page opens slow and other issues, playing a thread dump is the best way to solve the problem. That is called a thread dump thread stack, to obtain the thread stack has two steps:

1) to obtain the pid thread, you can use the jps command can also be used in the Linux environment ps -ef | grep java

2) Print thread stack, you can use jstack pid command in the Linux environment can also use kill -3 pid

Further mention that, Thread class provides a getStackTrace () method may also be used to obtain a thread stack. This is an instance method, so this method is specific and binding thread instance, every acquisition is to obtain a specific currently running thread stack.

 

3. how to detect whether a thread holding an object monitor

I was in line to see more than one thread face questions before we know there are ways to determine whether a thread holding an object monitor: Thread class provides a holdsLock (Object obj) method, if and only if the monitor is an object obj It returns the threads of time will hold true, that this is a static method, which means that "certain threads" refers to the current thread.

 

The difference 4.synchronized and ReentrantLock

It is synchronized and if, else, for, while the 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:

(1) ReentrantLock can set the waiting time to acquire the lock, thus avoiding the deadlock

(2) ReentrantLock may acquire various information lock

(3) ReentrantLock flexibility to achieve 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 degree of concurrency 5.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?

 

What is 6.ReentrantLock

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 7.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.

 

Under 8.Linux environment How to find which thread uses the CPU longest

This is a partial practical problems that I feel quite meaningless. You can do:

pid (1) acquisition project, jps or ps -ef | grep java, have talked about this in front

(2) top -H -p pid, the order can not be changed

So that you can print out the current project, each thread occupancy percentage of CPU time. Note that this play is the LWP, which is the operating system native threads thread, then I Notebook Hill did not deploy Java project under the Linux environment, so there is no way to capture the demo, users and friends if the company is using Linux environment deployment project, you can try a bit.

Use "top -H -p pid" + "jps pid" you can easily find a bar with a high CPU thread thread stack, thereby positioning occupy high CPU reasons, usually because of improper operation of the code results in an infinite loop.

Finally mention that, "top -H -p pid" break out of the LWP is decimal, "jps pid" break out of the local thread number is hexadecimal, convert it, you can navigate to the CPU-high thread the current thread stack up.

 

9. What happens if an exception to the emergence of a thread running

If the exception is not caught, then the thread is stopped executed. Another important point is this: If this thread holds a monitor of an object, then the object's monitor will be released immediately

 

10. How to share data between two threads

By sharing objects between threads on it, and then wait / notify / notifyAll, await / signal / signalAll be arouse and wait, say BlockingQueue blocking queue data is shared between threads and design

 

11. The difference between threads and processes?

There is at least one program to the next process, at least one thread at a process, under a process can have multiple threads to increase the execution speed of the program.

 

12. What is the guardian of threads are?

Daemon thread is running a special process in the background. It is independent of the control terminal and periodically perform some task or some events awaiting processing. In Java garbage collection thread is a special thread guard.

 

13. What are the different ways to create a thread?

There are three ways to create threads:

Thread re-run inherited methods;

Implement Runnable;

Implement Callable interface.

 

Say something runnable and callable 14. What is the difference?

runnable no return value, callable can get a return value, callable can be seen as a complement runnable.

 

15. What are the thread state?

State of the thread:

NEW has not yet started

RUNNABLE being implemented

BLOCKED blocked (synchronized locks or lock blocking IO)

WAITING permanent wait state

TIMED_WAITING waiting for a specified time to re-awakened state

TERMINATED execution is complete

 

16. sleep () and wait () What is the difference?

Different classes: sleep () from Thread, wait () from the Object.

Release the lock: sleep () does not release the lock; wait () releases the lock.

Use different: sleep () time to recover automatically; wait () can use the notify () / notifyAll () direct wake.

 

17. notify () and notifyAll () What is the difference?

Wake up a thread after notifyAll () wakes up all the threads, notify (). After notifyAll () call, all threads will be moved by the pool waiting for the lock pool, the lock and then participate in the competition, competing successfully proceed, if unsuccessful, to stay in the pool after the lock wait for a lock to be released to compete again. And notify () will only wake a thread, a thread which is controlled by a specific virtual machine wake.

 

18. The thread's run () and start () What is the difference?

start () method to start threads, run () method for operating when the code execution thread. run () can be called repeatedly, and start () can only be called once.

 

19. create a thread pool, which has several ways?

There are seven ways to create a thread pool, the core is the last:

newSingleThreadExecutor (): It is characterized by the number of worker threads is limited to 1, operating a unbounded work queue, so it ensures that all tasks are being executed in order, there will be up to a task is active and does not allow users examples of thread pool changes, which changes the number of threads can be avoided;

newCachedThreadPool (): It is a thread pool to handle a large number of short-term tasks, has several distinctive features: it will attempt to cache and reuse threads, cache when no thread is available, it will create a new worker thread; if thread idle time more than 60 seconds, were terminated and removed from the cache; idle for a long time, this thread pool, does not consume any resources. SynchronousQueue used as the internal work queue;

newFixedThreadPool (int nThreads): Reuse specified number (nThreads) thread behind the use of unbounded work queue at any time up to nThreads worker threads are active. This means that if the number of tasks exceeds the number of active queue, waiting for a free thread will appear in the work queue; if there are worker threads exit, there will be a new worker thread is created to make up the specified number nThreads;

newSingleThreadScheduledExecutor (): create a pool of single-threaded, The ScheduledExecutorService return, or periodic timing may work schedule;

newScheduledThreadPool (int corePoolSize): and newSingleThreadScheduledExecutor () Similarly, The ScheduledExecutorService is created, can be timed or periodic scheduling work, except that a single or a plurality of work worker threads;

newWorkStealingPool (int parallelism): This is an often overlooked thread pool, Java 8 before adding this to create a method that builds internal ForkJoinPool, the use of Work-Stealing algorithm, parallel processing tasks, does not guarantee the processing sequence;

ThreadPoolExecutor (): is the most primitive of the thread pool is created, the above steps to create ways that are packaged for the ThreadPoolExecutor.

 

20. What are the thread pool status?

RUNNING: This is the most normal state, to accept new tasks, processing of waiting tasks queue.

SHUTDOWN: do not accept the submission of new tasks, but will continue to deal with waiting tasks queue.

STOP: do not accept the submission of new tasks, wait no longer handle the task queue, interrupt threads are executing tasks.

TIDYING: all tasks are destroyed, workCount is 0, the state of the thread pool when converting to TIDYING state, will perform hook method terminated ().

TERMINATED: After terminated () method, the state will become the thread pool.

 

21. The thread pool submit () and execute () method What is the difference?

execute (): Runnable types of tasks can only be executed.

submit (): can execute Runnable and Callable types of tasks.

Callable types of tasks can be performed to obtain the return value, and execute Runnable no return value.

 

22. Java program how to ensure safe operation of multi-threaded?

Method One: Use safety classes, such as Java util concurrent lower classes...

Option two: automatic locking synchronized.

Method three: Use a manual lock Lock.

Manual lock exemplary Java code is as follows:

Lock lock = new ReentrantLock();

lock. lock();

try {

.. System out println ( "get lock");

} catch (Exception e) {

// TODO: handle exception

} finally {

.. System out println ( "lock release");

lock. unlock();

}

 

23. What is the principle of synchronized multi-threaded lock escalation is?

synchronized lock escalation principle: there is an object inside the head of a lock object threadid field, in the first visit of threadid is empty, jvm allowed to hold biased locking and threadid set to its thread id, when it will re-enter the first determine whether threadid consistent with its thread id, if consistent, you can directly use this object, and if not, then upgrade biased locking is a lightweight lock, the lock to get through the spin cycle of a certain number of times, after a certain number of times, if it is not normal get to the object you want to use, then it will upgrade the lock locks from lightweight to heavyweight, this process constitutes a synchronized lock upgrade.

The purpose of the upgrade lock: Lock escalation is a lock to bring order to minimize performance overhead. After optimization of Java 6 implementation of synchronized using a biased locking upgraded to lightweight to heavyweight and then upgrade lock lock manner, thus reducing the lock performance brought consumption.

 

24. What is a deadlock?

When both hold an exclusive lock a thread A, and attempts to acquire an exclusive lock b of the case thread B holds an exclusive lock b, and try to get an exclusive lock of a, AB two threads occur due to the need to hold each other the lock, which occurs obstruction, and we called the deadlock.

 

25. how to prevent a deadlock?

Make use tryLock (long timeout, TimeUnit unit) method (ReentrantLock, ReentrantReadWriteLock), set the timeout, the timeout can exit prevent deadlocks.

Try to use Java. Util. Concurrent concurrent classes instead of their own handwriting lock.

Minimize the use of lock granularity, try not to use the same lock several functions.

Minimizing synchronization code block.

 

26. ThreadLocal What is that? What are the usage scenarios?

ThreadLocal thread for each use of the variable to provide a copy of the independent variables, so each thread can independently change their copy without affecting other threads corresponding copy.

ThreadLocal use the classic scenario is a database connection and session management.

 

27. talk about synchronized to achieve the underlying principle?

synchronized is achieved by a pair of monitorenter / monitorexit instruction, monitor objects are basically synchronized unit. Before Java 6, is implemented entirely on internal monitor operating system mutex, because of the need to switch the user mode kernel mode, a synchronous operation is undifferentiated heavyweight operation, performance is very low. But when Java 6, Java virtual machine conducted a drastically improved, providing three different monitor implementation, which is often said that the three different locks: Lock biased (Biased Locking), lock and lightweight heavyweight lock, which greatly improved its performance.

 

What is the difference 28. synchronized and volatile that?

volatile modifier is variable; the synchronized is a modified classes, methods, code segments.

volatile visibility can be achieved only modify variables, it does not guarantee atomicity; synchronized and modifications can ensure visibility and atomic variables.

volatile will not cause obstruction thread; synchronized may cause obstruction thread.

 

29. synchronized and Lock What is the difference?

It can be synchronized to the class, method, locking block; the lock only to lock the block.

synchronized without having to manually obtain and release locks, easy to use, abnormal will automatically release the lock, will not cause a deadlock; and the lock needs its own lock and release the lock, if used improperly not unLock () to release the lock will result in death lock.

By Lock can know without success to obtain a lock, and synchronized it can not be done.

 

30. synchronized and ReentrantLock What is the difference?

Early implementation of synchronized relatively inefficient, compared to ReentrantLock, most scenes are quite different performance, but in Java 6 Dui synchronized been a lot of improvements.

The main differences are as follows:

ReentrantLock use more flexible, but must release the lock with the action;

ReentrantLock must manually obtain and release the lock, and synchronized without having to manually release and open the lock;

ReentrantLock lock block code only, and the modification method can be used for synchronized block of code and the like.

Variable volatile flag will not be optimized compiler; mark may be synchronized variable optimizing compiler.

 

31. talk about atomic principle?

The main use of atomic CAS (Compare And Wwap) and volatile and native methods to ensure atomic operations, so as to avoid the high cost of synchronized, greatly enhance the efficiency.

 

32. Thread class constructor, which is a static block the calling 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, for example, assume that the new Thread2 the Thread1, main function in the new Thread2, then:

Constructor 1) Thread2 static block is the main thread calls, Thread2 the run () method is invoked own Thread2

Constructor 2) Thread1 static blocks are called Thread2, Thread1 the run () method is invoked their Thread1

 

33. A method of synchronization and sync 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.

Through this article, I mention the extra point, although the scope of the better sync, but in the Java virtual machine optimization method still exists called lock coarsening, this method is to synchronize range increases. This is useful, for example StringBuffer, it is a thread-safe class, the most common natural append () method is a synchronous method, we write the code will be repeated append strings, which means that to be repeated lock -> unlock this performance disadvantage, because it means that the Java virtual machine to repeatedly switch between kernel mode and user mode on this thread, so Java virtual machine code that will repeatedly append method calls are a lock roughening operation, extended operation to append multiple craniocaudal append method, it becomes a large sync block, thus reducing the lock -> unlock times, effectively improve the efficiency of the code execution.

 

34. The high concurrent task execution time is short business how to use thread pool? How concurrency is not high, long-time business using task execution thread pool? High concurrency, how long time business execution services using a thread pool?

This is a problem I see in concurrent programming online, put this question on the last, I hope everyone can see and think about, because this is a very good, very practical, very professional. On this issue, a personal view is:

1) high concurrent, business task execution time short, the number of threads in the thread pool can be set to the number of CPU cores +1 reducing thread context switching

2) is not high concurrency, see separate tasks to be executed for a long time business area:

a) If the business is a long time focused on the IO operation, that is IO-intensive task, because the operation does not take up CPU IO, so do not let all the CPU retired and sit, you can increase the number of threads in the pool, let CPU handle more business

b) If the traffic is concentrated in a long time operation is calculated, which is computationally intensive tasks, that no solution, and (1) as it, the number of threads in the pool is set to be less, reducing the thread context switching

c) high concurrency, long-time business execution, the key to solving this type of task is not to thread pool but in the overall architecture design, to see whether they can do business inside some of the data cache is the first step, the second is to increase server step, as setting the thread pool, thread pool to set a reference to other relevant articles. Finally, a long time business execution problems, may also need to analyze it, see if you can use the middleware to split tasks and decoupling.

Guess you like

Origin www.cnblogs.com/Bkxk/p/11577517.html