1. What is the difference between a daemon thread and a local thread in java?
java There are two kinds of threads in: daemon thread( Daemon )And user threads( User ). Any thread can be set as daemon thread and user thread through method Thread.setDaemon(boolon) ; true The thread is set as a daemon thread, otherwise it is a user thread. Thread.setDaemon() Must be Thread.start() Before calling, otherwise the runtime throws an exception. The difference between the two: The only difference is to judge the virtual machine (JVM) When to leave, Daemon Is to provide services for other threads, if all User Thread Evacuated, Daemon There are no threads to serve, JVM evacuate. It can also be understood that the daemon thread is JVM Automatically created thread (but not necessarily), user thread is the thread created by the program; such as JVM The garbage collection thread is a guard thread. When all threads have been evacuated and no garbage is generated, the guard thread will naturally have nothing to do. When the garbage collection thread is Java When there are only threads left on the virtual machine, Java Virtual Opportunities leave automatically. Extension: Thread Dump The printed thread information contains daemon Threads with words are daemons, which may include: Service daemons, compilation daemons windows Monitoring under Ctrl+break Daemons Finalizer Daemons, reference processing daemons GC Daemons.
2. What is the difference between threads and processes?
Process is the smallest unit that the operating system allocates resources, and thread is the smallest unit that the operating system schedules. A program has at least one process , A process has at least one thread.
3. What is context switching in multithreading?
Multiple threads work together on a set of computers CPU ,The number of threads is greater than the number allocated to the program CPU In order for each thread to have the opportunity to execute, it needs to be rotated CPU . Switching between different threads CPU The switching data is context switching.
4. The difference between deadlock and livelock, the difference between deadlock and hunger?
Deadlock: it refers to the phenomenon that two or more processes (or threads) wait for each other due to competing for resources during execution. If there is no external force, they will not be able to move forward. Necessary conditions for deadlock generation: 1,Mutex condition: the so-called mutex is that the process monopolizes resources at a certain time. 2 ,Request and hold condition: when a process is blocked by requesting resources, it does not hold the obtained resources Let go. 3,Conditions of non deprivation : The process has obtained resources and cannot be forcibly deprived until they are used up. 4,Cycle waiting condition : A circular waiting resource relationship is formed between several processes. Livelock: the task or executor is not blocked. It is repeated because some conditions are not met Try, fail, try, fail. The difference between livelock and deadlock is that the entity in livelock is constantly changing state, the so-called "live", while the entity in deadlock is waiting; A live lock may unlock itself, but a deadlock cannot. Starvation: a state in which one or more threads are unable to obtain the required resources for various reasons, resulting in continuous inability to execute. Java Causes of hunger in: 1,High priority threads devour all low priority threads CPU Time. 2 ,The thread is permanently blocked in a state waiting to enter the synchronization block because other threads can always continuously access the synchronization block before it. 3,The thread is waiting for an object that itself is permanently waiting for completion(For example, call this object wait method),Because other threads are always continuously awakened.
5. What is the thread scheduling algorithm used in Java?
Time slice rotation is adopted. You can set the priority of the thread, which will be mapped to the priority above the lower system. If it is not specially needed, try not to use it to prevent thread hunger.
6. What is a thread group and why is it not recommended in Java?
ThreadGroup Class, which can assign threads to a thread group. Thread groups can have thread objects, thread groups, and threads. This organizational structure is somewhat similar to the form of a tree. Why not recommend it? Because there are many security risks in using it, there is no specific investigation. If it needs to be used, it is recommended to use thread pool.
7. Why use the Executor framework?
Create a thread each time a task is executed new Thread() Comparing the consumption performance, creating a thread is time-consuming and resource consuming. call new Thread() The created threads lack management and are called wild threads, and can be created without restrictions. The competition between threads will lead to excessive occupation of system resources and system paralysis. In addition, the frequent alternation between threads will also consume a lot of system resources. Connected use new Thread() The started thread is not conducive to expansion, such as regular execution, regular execution, regular execution, thread interrupt, etc.
8. What is the difference between Executors and Executors in Java?
Executors Different methods of the tool class create different thread pools according to our needs to meet the business needs. Executor The interface object can perform our thread tasks. ExecutorService Interface inherits Executor Interface and extended to provide more methods. We can obtain the execution status of the task and the return value of the task. use ThreadPoolExecutor You can create custom thread pools. Future Represents the result of asynchronous calculation. It provides a method to check whether the calculation is completed to wait for the completion of the calculation, and can be used get()Method to obtain the calculated results.
9. What is atomic operation? What are the atomic classes in the Java Concurrency API?
Atomic operation( atomic operation)One or a series of operations that cannot be interrupted. The processor implements atomic operations between multiprocessors based on cache locking or bus locking. stay Java Can be locked and cycled CAS To implement atomic operations. CAS Operation—— Compare & Set ,or Compare & Swap ,Now almost all CPU All instructions are supported CAS Atomic operations. Atomic operation refers to an operation task unit that is not affected by other operations. Atomic operation is a necessary means to avoid data inconsistency in multi-threaded environment. int++It is not an atomic operation, so when one thread reads its value and adds 1, another thread may read the previous value, which will cause an error. In order to solve this problem, we must ensure that the addition operation is atomic JDK1.5 Previously, we could use synchronization technology to do this. reach JDK1.5 , java.util.concurrent.atomic Package provides int and long Types of atomic wrapper classes that automatically guarantee that their operations are atomic and do not require synchronization. java.util.concurrent This package provides a set of atomic classes. Its basic feature is that in a multithreaded environment, when multiple threads execute the methods contained in the instances of these classes at the same time, it is exclusive, that is, when a thread enters the method and executes the instructions therein, it will not be interrupted by other threads, and other threads are like spin locks, waiting until the execution of the method is completed JVM It is only a logical understanding to select another thread from the waiting queue to enter. Atomic class: A tomi c B oolean , A tomi c I nte g er , A tomi c L on g , A tomi c R e f eren c e Atomic array: A tomi c I nte g er A rra y , A tomi c L ongA rra y , A tomi c R e f eren c e A rra y Atomic attribute updater: AtomicLongFieldUpdater , AtomicIntegerFieldUpdater , AtomicReferenceFieldUpdater solve ABA Atomic class of the problem: AtomicMarkableReference (By introducing a boolean To reflect whether there has been any change, AtomicStampedReference (By introducing a int To add to reflect whether there has been any change in the middle)
10. What is the Lock interface in the Java Concurrency API? What are its advantages over synchronization?
Lock Interface provides more extensible lock operation than synchronization method and synchronization block. They allow more flexible structures, can have completely different properties, and can support conditional objects of multiple related classes. Its advantages are: It can make the lock more fair This allows the thread to respond to an interrupt while waiting for a lock You can let the thread try to acquire the lock and return immediately or wait for a period of time when the lock cannot be acquired Locks can be acquired and released in different ranges and in different orders On the whole Lock yes synchronized An extended version of, Lock Provides unconditional, pollable(tryLock method),Timed(tryLock Parametric method),Interruptible(lockInterruptibly),Multi conditional queue(newCondition method)Lock operation. in addition Lock All implementation classes basically support unfair locks ( default ) And fair lock, synchronized Only unfair locks are supported. Of course, in most cases, unfair locks are an efficient choice
11. What is the Executors framework?
Executor Framework is a framework that invokes, schedules, executes and controls asynchronous tasks according to a set of execution policies. Unlimited thread creation can cause application memory overflow. So creating a thread pool is a better solution because you can limit the number of threads and recycle them. utilize Executors The framework can easily create a thread pool.
12. What is a blocking queue? What is the implementation principle of blocking queue? How to use blocking queue to implement producer consumer model?
Blocking queue( BlockingQueue)Is a queue that supports two additional operations. These two additional operations are: when the queue is empty, the thread getting the element will wait for the queue to become non empty. When the queue is full, the thread that stores the element waits for the queue to become available. Blocking queues are often used in the scenario of producers and consumers. Producers are threads that add elements to the queue, and consumers are threads that take elements from the queue. A blocking queue is a container where producers store elements, And consumers only take elements from containers. JDK7 Seven blocking queues are provided. namely: ArrayBlockingQueue : A bounded blocking queue consisting of an array structure. LinkedBlockingQueue : A bounded blocking queue composed of linked list structure. PriorityBlockingQueue : An unbounded blocking queue that supports prioritization. DelayQueue: An unbounded blocking queue implemented using priority queue. SynchronousQueue: A blocking queue that does not store elements. LinkedTransferQueue : An unbounded blocking queue composed of linked list structure. LinkedBlockingDeque : A bidirectional blocking queue composed of linked list structure. Java 5 In the previous implementation of synchronous access, a common collection can be used, and then the producer and consumer mode can be realized by using thread cooperation and thread synchronization. The main technology is to make good use of it, wait ,notify,notifyAll,sychronized These keywords. And in java 5 After that, the blocking queue can be used. This method greatly simplifies the amount of code, makes multi-threaded programming easier and ensures security. BlockingQueue Interface is Queue Its main purpose is not as a container, but as a tool for thread synchronization. Therefore, it has an obvious feature, When the producer thread attempts to BlockingQueue When putting an element, if the queue is full, the thread is blocked. When the consumer thread attempts to take an element out of it, if the queue is empty, the thread is blocked The process will be blocked. Because of this feature, multiple threads in the program alternate to each other BlockingQueue Put elements in and take out elements, which can well control the communication between threads signal communication. The most classic scenario for using blocking queues is socket For the reading and parsing of client data, the thread reading the data continuously puts the data into the queue, and then the parsing thread continuously takes the data from the queue for parsing.
13. What are Callable and Future?
Callable The interface is similar to Runnable ,You can tell from the name, but Runnable No result will be returned, and an exception that returns the result cannot be thrown, and Callable More powerful, After being executed by the thread, you can return a value, which can be Future Get it, that is, Future You can get the return value of the asynchronous execution task. It can be considered with callback Runnable. Future The interface represents asynchronous tasks and is the future result of unfinished tasks. So Callable Used to produce results, Future Used to get results.
14. What is FutureTask? Start the task using ExecutorService.
stay Java In concurrent programs FutureTask Represents an asynchronous operation that can be canceled. It has the methods of starting and canceling the operation, querying whether the operation is completed and retrieving the operation results. The result can be retrieved only when the operation is completed, if the operation is not completed get Method will block. One FutureTask Object can be called on Callable and Runnable The object is wrapped because FutureTask Also called Runnable Interface, so it can be submitted to Executor To execute.
15. What is the implementation of a concurrent container?
What is a synchronization container: it can be simply understood as through synchronized If multiple threads call the method of the synchronization container, they will execute serially. such as Vector, Hashtable ,as well as Collections.synchronizedSet , synchronizedList And other methods. You can view Vector , Hashtable Wait for the implementation code of these synchronization containers. You can see that the way these containers implement thread safety is to encapsulate their states and add keywords to the methods that need synchronization synchronized. The concurrent container uses a completely different locking strategy from the synchronous container to provide higher concurrency and scalability, such as in ConcurrentHashMap A locking machine with finer granularity is adopted in the In this locking mechanism, any number of read threads are allowed to access concurrently map ,And the threads that execute read operations and write operations can also be accessed concurrently map ,At the same time, a certain number of write threads are allowed to modify concurrently map,Therefore, it can achieve higher throughput in concurrent environment.
16. There are several ways to implement multithread synchronization and mutex. What are they?
Thread synchronization refers to a constraint relationship between threads. The execution of a thread depends on the message of another thread. When it does not get the message of another thread, it should wait until the message is received Wake up when you arrive. Thread mutex refers to the exclusivity of shared process system resources when accessed by a single thread. When several threads want to use a shared resource, any time Only one thread is allowed to use the resource at most. Other threads that want to use the resource must wait until the resource occupier releases the resource. Thread mutex can be regarded as a special thread synchronization. The synchronization methods between threads can be divided into two categories: user mode and kernel mode. As the name suggests, kernel mode refers to the use of the singleness of the system kernel object for synchronization, which needs to be cut when used Change the kernel state and user state, and the user mode does not need to switch to the kernel state, but only completes the operation in the user state. Methods in user mode are atomic operations (such as a single global variable) Quantity), critical zone. The methods in kernel mode are: event, semaphore and mutex.
17. What are the competitive conditions? How do you find and solve the competition?
When multiple processes attempt to process the shared data, and the final result depends on the running order of the processes, we think that a competitive condition occurs( race condition).
18. How will you use Thread dump? How will you analyze Thread dump?
New status( New) use new The thread created by the statement is in the new state, and it and other Java Object, only memory is allocated in the heap. Ready status( Runnable ) When a thread object is created, other threads call its start()Method, the thread enters the ready state, Java The virtual opportunity creates a method call stack and program counters for it. The thread in this state is in the runnable pool, waiting to get CPU Right to use. Running status( Running) Thread occupancy in this state CPU ,Execute program code. Only threads in the ready state have the opportunity to go to the running state. Blocking state( Blocked ) A blocking state is when a thread gives up for some reason CPU,Temporarily stop operation. When a thread is blocked, Java The virtual machine does not assign to threads CPU . It is not until the thread re enters the ready state that it has a chance to go to the running state. Blocking states can be divided into the following three types: Blocking state in object waiting pool( B lo c ked in obje c t ' s wait pool ): When the thread is running, if the execution of an object wait()method, Java The virtual machine will put the thread into the waiting pool of this object, which involves the content of "thread communication". Blocking state in object lock pool( B lo c ked in obje c t ' s lo c k pool ): When a thread is running and attempts to obtain the synchronization lock of an object, if the synchronization lock of the object has been occupied by other threads, Java The virtual machine will put the thread into the lock pool of the object, which involves "thread synchronization". Other blocking States( Otherwise Blocked): The current thread has executed sleep()Method, or a call to another thread join()Method, or issued I/O This state is entered when a request is made. Death state( Dead) When the thread exits run()Method, and the thread ends its life cycle.
19. Why do we execute the run() method when we call the start() method, and why can't we call the run() method directly?
When you call start()Method, you will create a new thread and execute it run()Method. But if you call directly run()Method, it will not create a new thread, nor execute the code calling the thread, but run Method is executed as a normal method.
20. How do you wake up a blocked thread in Java?
stay Java Used in the history of development suspend() , resume() Method to block and wake up threads, but there are many problems, typically deadlock. The solution can use object-oriented blocking, that is, using Object Class wait()and notify() Method to implement thread blocking. first, wait,notify Method is specific to the object and calls the of any object wait()Methods will lead to thread blocking. When blocking, it will also release the lock of the object. Accordingly, call the lock of any object notify()Method will randomly unblock the thread blocked by the object, but it needs to re acquire the lock of the changed object until it is successfully obtained; secondly, wait,notify Method must be in synchronized Block or method, and ensure that the lock object of the block or method is synchronized with the call wait,notify The object of the method is the same, so it is called wait The current thread has successfully obtained the lock of an object before execution wait After blocking, the current thread releases the previously acquired object lock.
21. What is the difference between cyclibariar and CountdownLatch in Java?
CycliBarriar Can be reused, and CountdownLatch Cannot be reused. Java of concurrent Inside the bag CountDownLatch In fact, it can be regarded as a counter, but the operation of this counter is an atomic operation. At the same time, only one thread can operate this counter, that is, only one thread can reduce the value in this counter at the same time. You can ask CountDownLatch Object sets an initial number as the count value, and any call on this object await()Methods will block, Until the count value of this counter is reduced to 0 by other threads. So before the current count reaches zero, await Methods will always be blocked. After that, all waiting threads will be released, await All subsequent calls to will return immediately. This happens only once - the count cannot be reset. If you need to reset the count, consider using CycliBarriar. CountDownLatch A very typical application scenario of is: a task wants to be executed, but it can't continue until other tasks are executed Go ahead. If we want to continue the task, call one CountDownLatch Object await() Method, the other tasks will be called after the execution of their own tasks. CountDownLatch On object countDown() Method, this call await() The task of the method will block and wait until this CountDownLatch The count value of the object is reduced to 0. CycliBarriar A synchronization helper class that allows a group of threads to wait for each other until they reach a common barrier point (common barrier point) . In a program involving a set of fixed size threads, these threads must wait for each other from time to time CycliBarriar Very useful. Because barrier After releasing the waiting thread, it can be reused, so it is called circular barrier.
22. What is an immutable object and how does it help write concurrent applications?
Immutable object (Immutable Objects) That is, once an object is created, its state (object data, that is, object attribute value) cannot be changed. On the contrary, it is a variable object(Mutable Objects). The class of an immutable object is an immutable class (Immutable Class) . Java The platform class library contains many immutable classes, such as S trin g ,Basic types of packaging BigInteger and BigDecimal Wait. Immutable objects are inherently thread safe. Their constants (fields) are created in the constructor. Since their state cannot be modified, these constants will never change. Immutable objects are always thread safe. An object is immutable only when the following states are satisfied:; Its status cannot be modified after creation; All domains are final Type; Also, it was created correctly (it did not occur during creation) this Escape of references).
23. What is context switching in multithreading?
During context switching, CPU It will stop processing the currently running program and save the specific location of the current program so that it can continue to run later. From this perspective, context switching is a bit like reading several books at the same time. While switching back and forth, we need to remember the page numbers of each book. In the program, the "page number" information in the context switching process is saved in the process control block( PCB)In. PCB It is also often called "switching frame"( switchframe ). " Page number information is saved until CPU In memory until they are used again. Context switching is storage and recovery CPU State, which enables thread execution to resume execution from the point of interruption. Context switching is a basic feature of multitasking operating system and multithreading environment.
24. What is the thread scheduling algorithm used in Java?
Computers usually have only one CPU,Only one machine command can be executed at any time , Each thread only gets CPU To execute the instruction . The so-called concurrent operation of multithreading , Actually, it means from a macro point of view , Each thread takes turns to get CPU Right to use , Perform their respective tasks . In run pool , There will be multiple ready threads waiting CPU,JAVA One task of virtual machine is to be responsible for thread scheduling , Thread scheduling refers to allocating resources to multiple threads according to a specific mechanism CPU Right to use . There are two scheduling models: time-sharing scheduling model and preemptive scheduling model. The time-sharing scheduling model means that all threads take turns to obtain cpu Right to use , And allocate each thread equally Occupied CPU This time slice is also easier to understand. Java The virtual machine adopts preemptive scheduling model, which means giving priority to the threads with high priority in the runnable pool CPU , If the threads in the runnable pool have the same priority, a thread is randomly selected to occupy CPU . A running thread runs until it has to give up CPU .
25. What is a thread group and why is it not recommended in Java?
Thread group and thread pool are two different concepts. Their roles are completely different. The former is to facilitate thread management, and the latter is to manage thread life cycle, reuse threads and reduce the overhead of creating and destroying threads.
26. Why is it better to use the Executor framework than to use applications to create and manage threads?
Why use Executor Thread pool framework 1 ,Create a thread each time a task is executed new Thread() Comparing the consumption performance, creating a thread is time-consuming and resource consuming. 2 ,call new Thread() The created threads lack management and are called wild threads, and can be created without restrictions. The competition between threads will lead to excessive occupation of system resources and system paralysis. In addition, the frequent alternation between threads will also consume a lot of system resources. 3 ,Direct use new Thread() The started thread is not conducive to expansion, such as regular execution, regular execution, regular execution, thread interrupt, etc. use Executor Advantages of thread pool framework 1 ,It can reuse existing and idle threads, so as to reduce the creation of Thread objects and reduce the overhead of dead threads. 2,It can effectively control the maximum number of concurrent threads, improve the utilization of system resources, and avoid excessive resource competition. 3,The framework already has timing, periodic, single thread, concurrency control and other functions. To sum up, the thread pool framework is used Executor It can better manage threads and provide system resource utilization.
27. How many methods can you implement a thread in java?
Inherit Thread class realization Runnable Interface realization Callable Interface, what needs to be implemented is call() method
28. How to stop a running thread?
How to use shared variables In this way, the shared variable is introduced because it can be used by multiple threads executing the same task as a signal to notify the execution of the interrupted thread. use interrupt Method to terminate a thread. If a thread is blocked by waiting for some event to happen, how to stop the thread? This often happens, such as when a thread is blocked because it needs to wait for keyboard input, or when a Thread.join()Method, or Thread.sleep()Method calls in the network ServerSocket.accept() Method, or called DatagramSocket.receive() Method can cause thread blocking and make the thread in a non runnable state, even in the main program Set the thread's shared variable to true,However, the thread cannot check the loop flag at this time, and of course, it cannot be interrupted immediately. Our advice here is not to use stop()Method, but use Thread Provided interrupt()Method, because although this method will not interrupt a running thread, it can make a blocked thread throw an interrupt exception, so that the thread ends the blocking state ahead of time and exits the blocking code.
29. What is the difference between notify() and notifyAll()?
When a thread enters wait After that, you have to wait for other threads notify/notifyall, use notifyall,Can wake up all in wait State of the thread so that it re enters the contention queue for the lock, and notify Only one can be awakened. If you are not sure, suggest notifyAll,prevent notigy Program exception caused by signal loss.
30. What is Daemon thread? What does it mean?
The so-called backstage (daemon) Thread refers to the thread that provides a general service in the background when the program is running, and this thread is not an indispensable part of the program. Therefore, when all non background threads end, the program terminates and kills all background threads in the process. Conversely, as long as any non background thread is still running, the program will not terminate. Must be invoked before the thread starts. setDaemon()Method to set it as a background thread. Note: the background process is not executing finally Clause is terminated run()method. For example: JVM The garbage collection thread is Daemon Threads, Finalizer It is also a daemon thread.
31. How does java realize the communication and cooperation between multithreads?
Interrupt and shared variables
32. What is a reentrant lock?
For example, the reentrancy of explicit locks public class UnReentrant{ Lock lock = new Lock(); public void outer(){ lock.lock(); inner(); lock.unlock(); } public void inner(){ lock.lock(); //do something lock.unlock(); } }Copy code outer Called in inner,outer It's locked first lock,such inner You can't get it anymore lock. Actually call outer The thread of has obtained lock Lock, but not in inner The obtained lock resources are reused in. This lock is called non reentrant. Reentrant means that a thread can enter any code block synchronized with the lock it already owns. synchronized , ReentrantLock They are reentrant locks, which relatively simplifies the development of concurrent programming.
33. When a thread enters a synchronized instance method of an object, can other threads enter other methods of the object?
If other methods do not synchronized If so, other threads can enter. Therefore, when you want to open a thread safe object, you must ensure that each method is thread safe.
34. Understanding and implementation of optimistic lock and pessimistic lock, and what are the implementation methods?
Pessimistic lock: always assume the worst case. Every time you go to get the data, you think others will modify it, so you lock it every time you get the data, so others will block the data until they get the lock. Many such locking mechanisms are used in traditional relational databases, such as row lock, table lock, read lock and write lock, which are locked before operation. Another example Java Synchronization primitives inside synchronized Keyword implementation is also a pessimistic lock. Optimistic lock: as the name suggests, it is very optimistic. Every time I go to get the data, I think others will not modify it, Therefore, it will not be locked, but when updating, it will judge whether others have updated this data during this period. You can use mechanisms such as version number. Optimistic locking is applicable to multi read application types, which can improve throughput, similar to that provided by the database write_condition Mechanisms, in fact, are optimistic locks provided. stay Java in java.util.concurrent.atomic The atomic variable class under the package is an implementation using optimistic locking CAS Implemented. Implementation method of optimistic lock: 1,The version ID is used to determine whether the read data is consistent with the data at the time of submission. Modify the version ID after submission. In case of inconsistency, discard and retry strategies can be adopted. 2 , java Medium Compare and Swap Namely CAS ,When multiple threads try to use CAS When the same variable is updated at the same time, only one thread can update the value of the variable Other threads fail. The failed thread will not be suspended, but will be told that it has failed in this competition and can try again. CAS There are three operands in the operation -- the inner that needs to be read and written Storage location( V),Expected original value for comparison( A)And the new value to be written(B). If memory location V The value of is different from the expected original value A Match, the processor will automatically change the position value New to new value B. Otherwise, the processor does nothing. CAS Disadvantages: 1,ABA Question: For example, a thread one From memory location V Remove from A,This is another thread two Also removed from memory A,also two After some operations, it becomes B,then two Will again V Location data becomes A,At this time, the thread one conduct CAS The operation found that the memory is still empty A,then one Operation succeeded. Although thread one of CAS The operation was successful, but There may be hidden problems. from Java1.5 start JDK of atomic A class is provided in the package AtomicStampedReference To solve ABA Question. 2,Long cycle time and high overhead: In case of serious resource competition (serious thread conflict), CAS The probability of spin will be higher, so more energy will be wasted CPU Resources, less efficient than synchronized. 3,Atomic operation of only one shared variable can be guaranteed: When performing operations on a shared variable, we can use loops CAS The way to ensure atomic operation, but when operating on multiple shared variables, the loop CAS You can't guarantee the atomicity of the operation. At this time, you can use a lock.
35. What is the difference between synchronized map and concurrent HashMap?
SynchronizedMap Lock the entire table at a time to ensure thread safety, so only one thread can visit at a time map. ConcurrentHashMap Segment lock is used to ensure performance under multithreading. ConcurrentHashMap One bucket at a time. ConcurrentHashMap Default will hash The table is divided into 16 barrels, such as get,put,remove Common operations such as lock only the bucket currently needed. In this way, only one thread can enter, but now 16 write threads can execute at the same time. The improvement of concurrency performance is obvious. in addition ConcurrentHashMap A different iterative approach is used. In this iterative approach, when iterator If the collection changes after it is created, it is no longer thrown ConcurrentModification Exception ,Instead, when it changes new New data so as not to affect the original data, iterator After completion, replace the header pointer with new data iterator Threads can use the original old data, and write threads can also change concurrently.
36. What application scenarios can CopyOnWriteArrayList be used for?
CopyOnWriteArrayList ( Lockless container ) One of the benefits of is that when multiple iterators traverse and modify the list at the same time, they will not throw ConcurrentModification Exception . stay CopyOnWriteArrayList In, writing will result in the creation of a copy of the entire underlying array, while the source array will remain in place, so that the read operation can be performed safely when the copied array is modified. 1 ,When writing, the array needs to be copied, which will consume memory. If the original array contains more contents, it may cause young gc perhaps full gc; 2 ,It cannot be used in real-time reading scenarios, such as copying arrays and adding new elements, which takes time, so call one set After the operation, the data read may still be old , although CopyOnWriteArrayList Can achieve final consistency ,However, it still can not meet the real-time requirements; CopyOnWriteArrayList Revealed ideas 1,Separate reading and writing, separate reading and writing 2,Final consistency 3,Use the idea of opening up space to solve concurrent conflicts
37. What is thread safety? Are servlet s thread safe?
Thread safety is a term in programming, which means that when a function or function library is called in a multithreaded environment, it can correctly handle the shared variables between multiple threads and make the program function complete correctly. Servlet Not thread safe, servlet It is single instance multithreaded. When multiple threads access the same method at the same time, the thread safety of shared variables cannot be guaranteed. Struts2 of action It is multi instance and multi-threaded. It is thread safe. Every request will come new A new action Assign to this request and destroy when the request is completed.
Is the Controller of spring MVC thread safe?
No, and Servlet Similar processing flow. Struts2 The advantage is that thread safety is not considered; Servlet and SpringMVC Thread safety needs to be considered, but the performance can be improved without dealing with too many problems gc,have access to ThreadLocal To deal with multithreading.
38. What's the use of volatile? Can you explain it in one sentence
volatile Application scenarios? volatile Ensure memory visibility and prohibit instruction rearrangement. volatile Used for single operation in multithreaded environment ( Single read or single write ) .
39. Why do codes reorder?
When executing a program, in order to provide performance, the processor and compiler often reorder the instructions, but they cannot reorder at will. Instead of sorting as you want, it needs to meet the following two conditions: the result of program operation cannot be changed in a single threaded environment; Reordering is not allowed if there are data dependencies. It should be noted that reordering will not affect the execution results in a single threaded environment, but will destroy the execution semantics of multiple threads.
40. What are the differences between wait and sleep methods in java?
The biggest difference is when waiting wai t Will release the lock, and sleep Always hold the lock. W ait It is usually used for inter thread interaction, sleep Usually used to suspend execution.
41. What happens if an exception occurs when a thread is running
If the exception is not caught, the thread will stop execution. Thread.UncaughtExceptionHandler It is an embedded interface used to handle sudden thread interruption caused by uncapped exceptions. When an uncapped exception will cause a thread interrupt JVM Can use Thread.getUncaughtExceptionHandler()To query the of the thread UncaughtExceptionHandler And pass the thread and exception as parameters to handler of uncaughtException()Method.
42. How to share data between two threads?
Variables can be shared between two threads. Generally speaking, shared variables require that the variables themselves are thread safe. When used in threads, if there are compound operations on shared variables, the thread safety of compound operations must also be guaranteed.
43. What is the difference between notify and notifyAll in Java?
notify() Method cannot wake up a specific thread, so it is only useful when a thread is waiting. and notifyAll()Waking up all threads and allowing them to compete for locks ensures that at least one thread can continue to run.
44. Why are the wait, notify and notifyAll methods not in the thread class?
One obvious reason is JAVA The locks provided are object level rather than thread level. Each object has a lock and is obtained through a thread. because wait,notify and notifyAll They are all lock level operations, so they are defined in Object Class because the lock belongs to an object.
45. What is ThreadLocal variable?
ThreadLocal yes Java A special variable in. Each thread has one ThreadLocal Each thread has its own independent variable, and the competition condition is completely eliminated. It is a good way to obtain thread safety for creating expensive objects. For example, you can use ThreadLocal Give Way SimpleDateFormat It becomes thread safe because the creation of that class is expensive and different instances need to be created for each call, so it is not worth using it locally. If each thread is provided with its own unique variable copy, the efficiency will be greatly improved. First, through reuse, the number of expensive objects is reduced. Second, you gain thread safety without using expensive synchronization or invariance.
46. What is the difference between interrupted and isInterrupted methods in Java?
interrupt Method is used to interrupt a thread. The state of the thread calling this method will be set to the "interrupt" state. Note: thread interrupt only sets the interrupt status bit of the thread and will not stop the thread. The user needs to monitor the status of the thread and handle it. Support the method of thread interruption (that is, it will be thrown after thread interruption interruptedException The method is to monitor the interrupt state of the thread. Once the interrupt state of the thread is set to "interrupt state", an interrupt exception will be thrown. interrupted Query the interrupt status of the current thread and clear the original status. If a thread is interrupted, the first call interrupted Then return true,The second and subsequent return false Yes. isInterrupted Just query the interrupt status of the current thread
47, what is the reason why wait and notify methods are invoked in synchronous blocks?
Java API This is mandatory, and if you don't, your code will throw IllegalMonitorStateException Abnormal. Another reason is to avoid wait and notify There are competing conditions between.
48. Why should you check the waiting conditions in the loop?
Threads in the waiting state may receive error alarms and false wakes. If the waiting conditions are not checked in the loop, the program will exit without meeting the end conditions.
49. What is the difference between synchronous sets and concurrent sets in Java?
Both synchronous collections and concurrent collections provide suitable thread safe collections for multithreading and concurrency, but concurrent collections have higher scalability. stay Java1.5 In the past, programmers only used synchronous sets, and it will lead to contention when multithreading is concurrent, which hinders the scalability of the system. Java5 This paper introduces the concurrent set image ConcurrentHashMap ,It not only provides thread safety, but also improves scalability with modern technologies such as lock separation and internal partition.
50. What is a thread pool? Why use it?
Creating a thread takes expensive resources and time. If a task comes to create a thread, the response time will be longer, and the number of threads a process can create is limited. In order to avoid these problems, when the program starts, several threads are created to respond to processing. They are called thread pools, and the threads in them are called worker threads. from JDK1.5 Start, Java API Provided Executor Framework allows you to create different thread pools.
51. How to detect whether a thread has a lock?
stay java.lang.Thread There is a method called holdsLock(),It returns true If and only if the current thread has a lock on a specific object.
52. How do you get the thread stack in Java?
kill -3 [java pid] It will not be output at the current terminal, but will be output to the place where the code is executed or specified. For example, kill -3 tomcat pid, Output stack to log Directory. Jstack [java pid] This is relatively simple. It can be displayed on the current terminal or redirected to the specified file. -JvisualVM : Thread Dump Open without instructions JvisualVM After, it is all interface operation, and the process is still very simple.
53. Which parameter in the JVM is used to control the small stack of threads?
Xss Stack size per thread
54. What is the function of the yield method in the Thread class?
Change the current thread from execution state (running state) to executable state (ready state). The current thread has reached the ready state, so which thread will change from the ready state to the execution state? It may be the current thread or other threads. It depends on the allocation of the system.
55. What is the concurrency of ConcurrentHashMap in Java?
ConcurrentHashMap Put actual map It is divided into several parts to realize its scalability and thread safety. This division is obtained by using concurrency, which is ConcurrentHashMap An optional parameter of class constructor, with the default value of 16, so that contention can be avoided in case of multithreading. stay JDK8 After that, it abandoned Segment (Lock segment), but enables a new way of implementation ,utilize CAS Algorithm. At the same time, more auxiliary variables are added to improve the concurrency. The specific content is to check Look at the source code.
56. What is Semaphore in Java?
Java Medium Semaphore Is a new synchronization class, which is a counting signal. Conceptually, semaphores maintain a set of permissions. If necessary, each is blocked before the license is available acquire(),Then obtain the license. each release()Adding a license may release a blocked acquirer. However, without using the actual license object, Semaphore Count only the number of licenses available and take appropriate action. Semaphores are often used in multithreaded code, such as database connection pools.
57. What is the difference between the submit() and execute() methods in the Java thread pool?
Both methods can submit tasks to the thread pool, execute()The return type of the method is void,It is defined in Executor Interface. and submit()Method can return the result of the calculation Future Object, which is defined in ExecutorService Interface, it extends Executor Interface, other thread pool classes like ThreadPoolExecutor and ScheduledThreadPoolExecutor There are these methods.
58. What is blocking method?
Blocking method means that the program will wait for the method to complete without doing anything else, ServerSocket of accept()The method is to wait for the client to connect. Blocking here means that the current thread will be suspended before the call result is returned and will not return until the result is obtained. In addition, there are asynchronous and non blocking methods that return before the task is completed.
59. What is ReadWriteLock in Java?
Read write lock is the result of lock separation technology used to improve the performance of concurrent programs.
60. What is the difference between volatile variables and atomic variables?
Volatile Variables ensure a look ahead relationship, that is, write operations occur before subsequent read operations , But it does not guarantee atomicity. For example, use volatile modification count Variable so count++ Operations are not atomic. and AtomicInteger Class atomic Method can make this operation atomic, such as getAndIncrement() Method will perform atomic incremental operation to add one to the current value. Other data types and reference variables can also perform similar operations.
61. Can I call the run () method of Thread class directly?
Certainly. But if we call Thread of run()Method, its behavior will be the same as that of ordinary methods, and will be executed in the current thread. In order to execute our code in a new thread, we must use Thread.start()method.
62. How to pause a running thread for a period of time?
We can use Thread Class Sleep()Method to pause the thread for a period of time. It should be noted that this does not terminate the thread. Once the thread is awakened from sleep, the state of the thread will be changed to Runnable,And according to the thread schedule, it will be executed.
63. What is your understanding of thread priority?
Each thread has priority. Generally speaking, high priority threads will have priority at runtime, but this depends on the implementation of thread scheduling, which is related to the operating system (OSdependent) . We can define the priority of threads, but this does not guarantee that high priority threads will execute before low priority threads. Thread priority is a int Variables(From 1-10),1 Represents the lowest priority and 10 represents the highest priority. java Thread priority scheduling will be entrusted to the operating system, so it has priority with the specific operating system Level. Generally, there is no need to set thread priority unless it is specially required.
64. What are thread scheduler and Time Slicing?
Thread scheduler is an operating system service, which is responsible for Runnable Thread allocation of state CPU Time. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. As for the same problem, thread scheduling is not affected Java Virtual machine control, so it's better for the application to control it (that is, don't let your program depend on it) Priority of the thread). Time slicing refers to the time that will be available CPU Time allocated to available Runnable Thread process. distribution CPU The time can be based on the thread priority or the time the thread waits.
65. How do you ensure that the thread where the main() method is located is the last thread of the Java program?
We can use Thread Class join()Method to ensure that all threads created by the program main() Method ends before exiting.
66. How do threads communicate?
When resources can be shared among threads, inter thread communication is an important means to coordinate them. Object In class wait()\notify()\notifyAll()Method can be used to communicate between threads about the state of a lock on a resource.
67. Why are the thread communication methods wait(), notify() and notifyAll() defined in the Object class?
Java There is a lock in each object of the(monitor,It can also be a monitor) also wait(),notify()And other methods are used to wait for the lock of the object or notify the supervisor of other thread objects The camera is available. stay Java There are no locks and synchronizers available to any object in thread. That's why these methods are Object Class, so Java Every class of There are basic methods for inter thread communication.
68. Why must wait(), notify() and notifyAll() be called in the synchronization method or synchronization block?
When a thread needs to call the object wait()Method, the thread must own the lock of the object, and then it will release the lock of the object and enter the waiting state until called by other threads On this object notify()method. Similarly, when a thread needs to call the object's notify()Method, it will release the lock of this object so that other waiting threads can Get this object lock. Since all these methods require threads to hold locks on objects, they can only be implemented through synchronization, so they can only be called in synchronization methods or synchronization blocks Use.
69. Why are the sleep() and yield () methods of Thread class static?
Thread Class sleep()and yield()Method will run on the thread currently executing. So it makes no sense to call these methods on other waiting threads. That's it Is why these methods are static. They can work in the currently executing thread and avoid programmers mistakenly thinking that they can call these methods in other non running threads.
70. How to ensure thread safety?
stay Java There are many ways to ensure thread safety -- synchronization, using atomic classes(atomicconcurrent classes),Implement concurrent locks, using volatile Keyword, using invariant classes and thread safe classes.
71. Which is the better choice of synchronization method and synchronization block?
Synchronization block is a better choice because it won't lock the whole object (of course, you can let it lock the whole object). Synchronization methods lock the entire object, even if there are multiple unrelated objects in this class Associated synchronization blocks, which usually causes them to stop execution and need to wait to obtain the lock on this object. Synchronization blocks should conform to the principle of open call, and only lock the corresponding code blocks that need to be locked From the side, deadlock can also be avoided.
72. How to create a daemon thread?
use Thread Class setDaemon(true) Method can set the thread as a daemon thread. Note that you need to call start()This method is called before the method is thrown, otherwise it will be thrown. IllegalThreadStateException Abnormal.
73. What is the Java Timer class? How to create a task with a specific time interval?
java.util.Timer Is a tool class that can be used to schedule a thread to execute at a specific time in the future. Timer Class can be used to schedule one-time tasks or periodic tasks. java.util.TimerTask It's an implementation Runnable Interface, we need to inherit this class to create our own scheduled tasks and use it Timer To arrange Implementation of.