Java concurrent programming

1. What is the difference between daemon threads and local threads in Java?

What is the difference between a thread and a process?

3. What is context switching in multithreading?

4. The difference between deadlock and live lock, deadlock and starvation?

5. What is the thread scheduling algorithm used in Java?

6. What are thread groups and why are they not recommended in Java?

7. Why use Executor Framework?

The difference between Exector and Executors in Java?

How to find which thread is using the most CPU time on Windows and Linux?

10. What is atomic operation? What atomic classes are available in the Java Concurrency API?

What is the Java Concurrency API’s Lock interface? What are the advantages over synchronization?

12. What is Executors Framework?

What is a blocking queue? What is the implementation principle of blocking queues? How to implement the producer-consumer model using blocking queues?

14. What are Callable and Future?

15. What is FutureTask? Start tasks using the ExecutorService.

What is the implementation of concurrent containers?

17, There are several ways to implement multithreaded synchronization and mutex. What are they?

What are the conditions of competition? How do you find and solve competition?

How will you use Thread dump? How would you analyze Thread dump?

20. Why do we call run() when we call start()? Why can’t we call run() directly?

21. How do you wake up a blocked thread in Java?

22. What is the difference between CycliBarriar and CountdownLatch in Java?

23. What are immutable objects and how does it help write concurrent applications?

24, What is context switching in multithreading?

25. What is the thread scheduling algorithm used in Java?

26. What are thread groups and why are they not recommended in Java?

27. Why is using the Executor framework better than using applications to create and manage threads?

28. How many ways can you implement a thread in Java?

29. How do I stop a running thread?

What is the difference between notify() and notifyAll()?

31. What are Daemon threads? What does it mean?

Java how to achieve communication and collaboration between multiple threads?

33. What is a ReentrantLock?

34. When a thread accesses a synchronized instance of an object, can other threads access other synchronized methods?

Optimistic lock and pessimistic lock understanding and how to achieve, what is the way to achieve?

What is the difference between SynchronizedMap and ConcurrentHashMap?

37. What application scenarios can CopyOnWriteArrayList be used for?

What is thread safety? Are servlets thread-safe?

39. What is volatile for? Can you explain in one sentence how volatile is used?

40. Why is code reordered?

41, What is the difference between wait and sleep in Java?

Using Java to implement blocking queues

43. What happens when an exception occurs while a thread is running?

44. How do I share data between two threads?

45. What is the difference between notify and notifyAll in Java?

46. Why don’t Wait, notify, and notifyAll belong to Thread?

47. What are ThreadLocal variables?

What is the difference between the interrupted and isInterrupted methods in Java?

49. Why are wait and notify called in a synchronized block?

50. Why should you check the wait condition in a loop?

What is the difference between synchronous and concurrent collections in Java?

What is a thread pool? Why use it?

How do I check if a thread has a lock?

54. How do you get a thread stack in Java?

56. What is the yield method for Thread?

What is the concurrency of ConcurrentHashMap in Java?

What is Semaphore in Java?

59, What is the difference between submit() and execute() methods in Java thread pools?

60. What are blocking methods?

What is ReadWriteLock in Java?

62. What is the difference between volatile variables and atomic variables?

63. Can I call the run () method of Thread directly?

64. How do I suspend a running thread for a period of time?

What is your understanding of thread priority?

66. What are Thread Scheduler and TimeSlicing?

67. How do you ensure that the thread on which the main() method is located is the last thread to terminate a Java program?

How do threads communicate with each other?

69. Why are the methods wait(), notify(), and notifyAll() defined in Object?

70. Why must wait(), notify(), and notifyAll () be called in synchronized methods or blocks?

71. Why are Thread sleep() and yield () static?

How to ensure thread safety?

Which is a better choice, synchronous method or synchronous block?

How do I create a daemon thread?

What is the Java Timer class? How do I create a task with a specific time interval?





Java concurrent programming knowledge summed up a mind map to share with you



1. What is the difference between daemon threads and local threads in Java?

There are two types of threads in Java: daemons and User threads.

Any Thread can be set to daemon and user threads using the thread.setdaemon (Boolon) method; True sets the thread to daemon or user. Thread.setdaemon () must be called before Thread.start(), otherwise the runtime will throw an exception.

The difference between the two:

The only difference is to determine when a virtual machine (JVM) has left. Daemons serve other threads. If all User threads have left and there are no threads available, the JVM exits. Daemon threads are threads created automatically by the JVM (but not necessarily), and user threads are threads created by the program. For example, the JVM’s garbage collector thread is a daemon thread. When all threads have been evacuated and no more garbage is generated, the daemon thread has nothing to do. When the garbage collector thread is the only thread left on the Java virtual machine, the Java virtual machine automatically leaves.

Thread dumps information about printed threads. A Thread containing the word daemon is a daemon process. Service daemons, build daemons, Ctrl+break daemons for Windows, Finalizer daemons, reference handling daemons, GC daemons.

What is the difference between a thread and a process?

Process is the smallest unit of operating system allocation of resources, thread is the smallest unit of operating system scheduling.

A program has at least one process, and a process has at least one thread.

3. What is context switching in multithreading?

Multiple threads share the CPUS on a set of computers, and when the number of threads is greater than the number of cpus allocated to the program, the CPU needs to be rotated so that each thread has a chance to execute. Switching data between different threads using the CPU is a context switch.

4. The difference between deadlock and live lock, deadlock and starvation?

Deadlock: A situation in which two or more processes (or threads) are waiting for each other to execute because they are competing for resources and cannot proceed without external forces.

The necessary conditions for a deadlock to occur:

Mutual exclusion conditions: Mutual exclusion is when a process monopolizes resources for a certain period of time.

2. Request and hold conditions: when a process is blocked by requesting resources, it holds on to acquired resources.

3, non-deprivation conditions: the process has obtained resources, before the end of the use, can not be forcibly deprived.

4. Circular waiting condition: a circular waiting resource relationship is formed between several processes.

Live lock: a task or performer that is not blocked is repeatedly tried, failed, tried, failed because some condition is not met.

The difference between a live lock and a deadlock is that an entity in a live lock is in a state of constant change, called “alive”, while an entity in a deadlock is waiting; Live locks can unlock themselves, deadlocks cannot.

Hunger: A state in which one or more threads are unable to execute because they cannot get the resources they need for any reason.

Causes of hunger in Java:

1. High-priority threads eat up all low-priority threads’ CPU time.

2. A thread is permanently blocked in a state waiting to enter a synchronized block because other threads can always access the synchronized block before it does.

3. A thread is waiting for an object that is itself permanently waiting to complete (such as calling its wait method) because other threads are constantly being woken up.

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 of the lower system. If you do not need it, do not use it to prevent thread hunger.



6. What are thread groups and why are they not recommended in Java?

The ThreadGroup class allows threads to be grouped into a ThreadGroup, which can have thread objects, thread groups, and threads in a tree-like structure.

Why not? Because there are many security risks, there is no specific investigation, if you need to use the thread pool is recommended.

7. Why use Executor Framework?

New threads () are created for each task. Creating a Thread is time consuming and resource consuming.

The threads created by calling new threads () are poorly managed, called wild threads, and can be created without limit. Competition between threads will lead to excessive use of system resources, resulting in system breakdown, and frequent alternation between threads will consume a lot of system resources.

Connecting threads started with new threads () is not scalable, such as scheduled execution, scheduled execution, scheduled execution, Thread interruption, etc.

The difference between Exector and Executors in Java?

Different methods of the Executors tool class created different thread pools according to our requirements to meet business requirements.

The Executor interface object can perform our threading tasks.

The ExecutorService interface extends and inherits the Executor interface, providing additional methods for obtaining the status of tasks executed and the return value of tasks.

Custom thread pools can be created using ThreadPoolExecutor.

The Future represents the result of an asynchronous calculation, which provides a way to check that the calculation is complete while waiting for it to complete, and to get the result of the calculation using the get() method.

How to find which thread is using the most CPU time on Windows and Linux?

10. What is atomic operation? What atomic classes are available in the Java Concurrency API?

An atomic operation means “an operation or series of operations that cannot be interrupted”.

The processor implements atomic operations between multiple processors based on cache locking or bus locking. Atomic operations can be implemented in Java by locking and looping CAS. CAS operations — Compare & Set, or Compare & Swap — are now supported by almost all CPU instructions.

An atomic operation is an operational task unit that is not affected by other operations. Atomic manipulation is a necessary means to avoid data inconsistencies in multithreaded environments.

Int++ is not an atomic operation, so when one thread reads its value and increments by one, another thread may read the previous value, which raises an error.

To solve this problem, it is necessary to ensure that increment operations are atomic, which we could do using synchronization techniques prior to JDK1.5. To JDK1.5, Java. Util. Concurrent. Atomic package provides an int and long types of atomic wrapper classes, they can be automatically guarantee for their operation is atomic and don’t need to use the synchronization.

The java.util.concurrent package provides a set of atomic classes. The basic feature is that in a multithreaded environment, when multiple threads execute the methods contained in the instance of these classes at the same time, it has exclusivity. That is, when one thread enters the method and executes its instructions, it will not be interrupted by other threads, while other threads, like spinlocks, wait until the method completes. It is only logical that the JVM selects one thread from the wait queue to enter another.

AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference

Atomic arrays: AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray

Atomic properties updater: AtomicLongFieldUpdater AtomicIntegerFieldUpdater, AtomicReferenceFieldUpdater

Atomic classes that solve ABA problems: AtomicMarkableReference (introduce a Boolean to indicate whether the middle has changed), AtomicStampedReference (add an int to indicate whether the middle has changed)

What is the Java Concurrency API’s Lock interface? What are the advantages over synchronization?

The Lock interface provides a more extensible locking operation than synchronized methods and synchronized blocks.

They allow for more flexible structures that can have radically different properties, and can support conditional objects of multiple related classes.

Its advantages include:

Can make locks fairer

Threads can be made to respond to interrupts while waiting for locks

You can have a thread attempt to acquire the lock and either return immediately or wait a certain amount of time if the lock cannot be acquired

Locks can be acquired and released in different order in different scopes

Lock is generally an extension of synchronized, Lock provides unconditional, pollable (tryLock method), timed (tryLock parameterized method), interruptibly (lockInterruptibly), and multi-conditional queued (newCondition method) Lock operations. In addition, Lock implementation classes basically support unfair Lock (default) and fair Lock, synchronized only supports unfair Lock, of course, in most cases, unfair Lock is an efficient choice.

12. What is Executors Framework?

The Executor framework is a framework for invoking, scheduling, executing, and controlling asynchronous tasks based on a set of execution policies.

Unlimited creation threads cause an application memory overflow. Creating a thread pool is a better solution because you can limit the number of threads and recycle them. Create a thread pool very easily by using the Executors framework.

What is a blocking queue? What is the implementation principle of blocking queues? How to implement the producer-consumer model using blocking queues?

A BlockingQueue is a queue that supports two additional operations.

The two additional operations are: when the queue is empty, the thread that fetched the element waits 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 producer and consumer scenarios, where the producer is the thread that adds elements to the queue and the consumer is the thread that takes elements from the queue. A blocking queue is a container in which producers hold elements, and consumers only take elements from the container.

JDK7 provides seven blocking queues. Respectively is:

ArrayBlockingQueue: A bounded blocking queue composed of array structures.

LinkedBlockingQueue: A bounded blocking queue consisting of a linked list structure.

PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.

DelayQueue: an unbounded blocking queue implemented using a priority queue.

SynchronousQueue: A blocking queue that does not store elements.

LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure.

LinkedBlockingDeque: A bidirectional blocking queue consisting of a linked list structure.

Java 5 synchronization access, before you can use the ordinary a collection, and then using a thread of collaboration and thread synchronization can realize producers, consumer model, main technology is to use good, wait, notify, notifyAll, sychronized these keywords. After Java 5, blocking queues can be used to achieve this, which greatly reduces the amount of code, making multithreaded programming easier and safer.

The BlockingQueue interface is a subinterface to a Queue. Its main purpose is not as a container, but as a tool for thread synchronization. Therefore, it has the obvious feature that when a producer thread tries to put an element into the BlockingQueue, if the Queue is full, the thread will block. When a consumer thread tries to retrieve an element from the BlockingQueue, if the queue is empty, the thread will block. Because of this feature, it can control the communication between threads by alternately adding and removing elements from the BlockingQueue.

The most classic scenario of blocking queue usage is data reading and parsing on the Socket client. The reading thread keeps putting data into the queue, and the parsing thread keeps retrieving data from the queue for parsing.

14. What are Callable and Future?

The Callable interface is similar to Runnable, as the name suggests, but Runnable does not return a result and cannot throw an exception that returns a result. Callable is more powerful, and when executed by a thread, it can return a value, which can be retrieved by the Future. That is, the Future can get the return value of the asynchronously executed task.

Think of it as Runnable with a callback.

The Future interface represents asynchronous tasks that are Future results of tasks that have not yet been completed. So Callable is used to produce results and Future is used to get results.

15. What is FutureTask? Start tasks using the ExecutorService.

In Java concurrent programs, FutureTask represents an asynchronous operation that can be cancelled. It has methods to start and cancel operations, to check whether an operation is complete, and to retrieve the result of an operation. The result can only be retrieved when the operation is complete, and the GET method will block if the operation is not complete. A FutureTask object can wrap objects that call Callable and Runnable, and since FutureTask also calls the Runnable interface, it can be submitted to Executor for execution.

What is the implementation of concurrent containers?

What a synchronized container is: A container that can be understood simply as synchronized. If multiple threads call the synchronized container methods, they are executed serially. Such as Vector, Hashtable, and Collections. SynchronizedSet synchronizedList method such as returned by the container. By looking at the implementation code for Vector, Hashtable, and other synchronized containers, you can see that these containers achieve thread-safety by encapsulating their state and adding the keyword synchronized to the methods that need to be synchronized.

Concurrent containers use a completely different locking strategy from synchronous containers to provide higher concurrency and scalability. For example, in ConcurrentHashMap, a more fine-grained locking mechanism is used, which can be called segment-based locking. In this locking mechanism, any number of readers are allowed to access the map concurrently. In addition, the read thread and the write thread can concurrently access the map, while allowing a certain number of write threads to concurrently modify the map, so it can achieve higher throughput in a concurrent environment.

17, There are several ways to implement multithreaded synchronization and mutex. What are they?

Thread synchronization refers to a restriction relationship between threads. The execution of one thread depends on the message of another thread. When it does not receive the message of another thread, it should wait until the message arrives and is woken up. Thread mutex refers to the exclusive access of individual threads to shared process system resources. When several threads are using a shared resource, only one thread is allowed to use it at any time, and other threads must wait until the hogger releases the resource. Thread mutex can be thought of as a special kind of thread synchronization.

Synchronization methods between threads can be broadly divided into two categories: user-mode and kernel-mode. As the name implies, kernel mode refers to the use of the system kernel object singleness to synchronize, the use of the need to switch between the kernel state and the user state, and user mode is not required to switch to the kernel state, only in the user state to complete the operation.

Methods in user mode include: atomic operations (such as a single global variable), critical sections. Kernel-mode methods include events, semaphores, and mutex.

What are the conditions of competition? How do you find and solve competition?

A race condition occurs when multiple processes attempt to perform some kind of processing on shared data, and the final outcome depends on the order in which the processes run.

How will you use Thread dump? How would you analyze Thread dump?

New State (New)

The thread created with the new statement is in the newly created state, where it is allocated only memory in the heap, just like any other Java object.

Runnable state

When a thread object is created and other threads call its start() method, the thread enters the ready state and the Java virtual machine creates a method call stack and program counters for it. Threads in this state are in the runnable pool, waiting to acquire CPU usage.

Running Status

Threads in this state occupy the CPU and execute program code. Only threads in the ready state have a chance to go to the run state.

The state of being Blocked

A blocked state is when a thread abandons the CPU for some reason and stops running temporarily. When a thread is blocked, the Java virtual machine does not allocate CPU to the thread. Until the thread re-enters the ready state, it has no chance to move to the running state.

The blocking state can be divided into the following three types:

Blocked in an object’s wait pool:

When a thread is running, the Java virtual machine places the thread in the object’s wait pool if it executes its wait() method, which involves “thread communication.”

Blocked in an object’s lock pool:

When a thread tries to acquire a synchronization lock on an object while it is running, the Java virtual machine will add the thread to the lock pool of the object if the synchronization lock is already occupied by another thread. This involves “thread synchronization”.

Otherwise Blocked:

This state occurs when the current thread executes the sleep() method, or calls another thread’s join() method, or makes an I/O request.

Dead state

When a thread exits the run() method, it enters a dead state and the thread terminates its life cycle.



20. Why do we call run() when we call start()? Why can’t we call run() directly?

When you call the start() method you will create a new thread and execute the code in the run() method.

But if you call the run() method directly, it doesn’t create a new thread or execute the code that calls the thread. It just executes the run method as if it were a normal method.

21. How do you wake up a blocked thread in Java?

In the history of Java, methods suspend() and resume() were used to block and wake up threads. However, many problems occurred, such as deadlock.

The solution can use object-targeted blocking, that is, thread blocking using the Wait () and notify() methods of the Object class.

Calling wait() on any object will block and release the lock on that object. Calling notify() on any object will release the lock on that object at random. Do not proceed until success is achieved; Second, the wait and notify methods must be called in a synchronized block or method, and the lock object on the synchronized block or notify method must be the same as that on the synchronized block or notify method, so that the current thread has successfully acquired the lock on the object before invoking wait. To block, the current thread releases the lock on the previously acquired object.

22. What is the difference between CycliBarriar and CountdownLatch in Java?

CyclicBarrier can be reused, but CountdownLatch cannot.

The CountDownLatch in the Concurrent package in Java can be viewed as a counter, except that the counter operation is atomic and only one thread can operate on the counter at a time, i.e., only one thread can reduce the value of the counter. You can set an initial number to the CountDownLatch object as the count, and any calls to await() on the object will block until the count of the counter has been reduced to zero by another thread.

So the await method will block until the current count reaches zero. After that, all waiting threads are released and all subsequent calls to the await are returned immediately. This happens only once — the count cannot be reset. If you need to reset the count, consider using CyclicBarrier. A very typical use of CountDownLatch is when you have a task that you want to move down, but you can’t move down until all the other tasks have finished. If the task we want to continue calls the await() method of the CountDownLatch object and the other tasks call the countDown() method of the same CountDownLatch object after executing their own tasks, The task calling the await() method will block and wait until the count of the CountDownLatch object decreases to zero.

CyclicBarrier A synchronization helper class that allows a group of threads to wait for each other until a common barrier point is reached. Cyclicbarriers are useful in programs that involve a set of threads of a fixed size that must wait for each other from time to time. Because this barrier can be reused once the waiting thread is freed, it is called a cyclic barrier.

23. What are immutable objects and how does it help write concurrent applications?

Immutable Objects are Mutable Objects that cannot change their state (their data, or property values) once they are created.

Classes of Immutable objects are Immutable classes. The Java platform class library contains immutable classes such as String, primitive wrapper classes, BigInteger, and BigDecimal.

Immutable objects are inherently thread-safe. Their constants (fields) are created in the constructor. Since their state cannot be changed, these constants never change.

Immutable objects are always thread-safe.

An object is immutable only if it is;

Its state cannot be changed after creation;

All fields are final; And, it was created correctly (no escape of this reference occurred during creation).

24, What is context switching in multithreading?

During a context switch, the CPU stops processing the currently running program and saves the exact location of the current program for later execution. From this point of view, context switching is a bit like reading several books at the same time. We need to remember the current page number of each book as we switch back and forth. In a program, the “page number” information during the context switch is stored in the process control block (PCB). A PCB is also often referred to as a switchframe. Page numbers are stored in the CPU’s memory until they are used again.

Context switching is the process of storing and restoring CPU state that allows threaded execution to resume execution from a breakpoint. Context switching is a basic feature of multitasking operating systems and multithreaded environments.

25. What is the thread scheduling algorithm used in Java?

Computers typically have only one CPU and can execute only one machine instruction at any time, and each thread can execute instructions only if it has access to the CPU. The concurrent running of the so-called multithreading, in fact, is to point to from the macro view, each thread in turn to obtain the use of CPU, respectively to execute their respective tasks. In the run pool, there are multiple threads in a ready state waiting for the CPU, and one of the tasks of the JAVA virtual machine is to be responsible for thread scheduling, which allocates CPU usage to multiple threads according to a specific mechanism.

There are two scheduling models: time-sharing and preemptive scheduling.

A time-sharing scheduling model is one in which all threads take turns to acquire CPU usage and allocate the CPU time slice equally for each thread.

Java virtual machines use a preemptive scheduling model, which means that the threads with the highest priority in the runnable pool occupy the CPU first. If the threads in the runnable pool have the same priority, a random thread is selected to occupy the CPU. A running thread runs until it has to abandon the CPU.

26. What are thread groups and why are they not recommended in Java?

Thread group and thread pool are two different concepts, their functions are completely different, the former is to facilitate the management of threads, the latter is to manage the life cycle of threads, reuse threads, reduce the cost of creating and destroying threads.





27. Why is using the Executor framework better than using applications to create and manage threads?

Why use the Executor thread pool framework

1. Create a new Thread() each time you execute a task.

2. The threads created by calling new threads () lack management, which is called wild threads and can be created without limit. Competition between threads will lead to excessive occupation of system resources and system breakdown, and frequent alternation between threads will consume a lot of system resources.

Threads started directly with new threads () are not scalable, such as scheduled execution, scheduled execution, scheduled execution, Thread interruption, etc.

Advantages of using the Executor thread pool framework

1. Reuse existing and idle threads to reduce the creation of thread objects and thus reduce the overhead of dead threads.

2, can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, while avoiding too much resource competition.

3. There are functions such as timing, periodic, single thread and concurrency control in the framework.

In summary, using Executor, a thread pool framework, provides better thread management and system resource utilization.

28. How many ways can you implement a thread in Java?

Thread class inheritance

Implement the Runnable interface

To implement the Callable interface, you need to implement the Call () method

29. How do I stop a running thread?

How to use shared variables

In this way, a shared variable is introduced because it can be used by multiple threads performing the same task as an interrupt signal to inform the interrupt thread of its execution.

Terminate a thread with the interrupt method

If a thread is blocked waiting for something to happen, how do you stop it? This often happens when a Thread is blocked because it needs to wait for keyboard input, or when thread.join () is called, or thread.sleep () is called, or serversocket.accept () is called in a network, Or a call to datagramsocket.receive () can block the thread, leaving it in an unrunnable state that, even if the main program sets the thread’s shared variable to true, cannot check for the loop flag and therefore cannot immediately interrupt. Our advice here is to avoid using the stop() method and instead use the interrupt() method provided by Thread, because while this method does not interrupt a running Thread, it can cause a blocked Thread to throw an interrupt exception, causing the Thread to end the blocking state prematurely and exit the blocking code.

What is the difference between notify() and notifyAll()?

When a thread enters a wait, it must wait for notify/ NotifyAll. Notifyall awakens all threads in wait state to re-enter the lock contention queue. Notifyall awakens only one thread.

If not, notifyAll is recommended to prevent Notigy from causing program exceptions due to signal loss.

31. What are Daemon threads? What does it mean?

A daemon thread is a thread that provides a common service in the background while a program is running and is not an integral part of the program. Therefore, when all non-background threads terminate, the program terminates, killing all background threads in the process. Conversely, the program does not terminate as long as any non-background threads are running. The setDaemon() method must be called before the thread is started to set it up as a background thread. Note: The background process terminates its run() method without executing the finally clause.

For example, JVM garbage collection threads are Daemon threads and Finalizer threads are also Daemon threads.

Java how to achieve communication and collaboration between multiple threads?

Interrupt and share variables

33. What is a ReentrantLock?

To illustrate the reentrancy of locks

public class UnReentrant{
	Lock lock = new Lock();
	public void outer(){
		lock.lock();
		inner();
		lock.unlock();
	}
	public void inner(){
		lock.lock();
		//dosomething lock.unlock(); }}Copy the code
Outer calls inner, which locks the lock so that inner can no longer get the lock. Reentrant means that a thread can access any block of code that is synchronized with the lock it already owns.

Synchronized and ReentrantLock are reentrant locks, which simplify the development of concurrent programming.

34. When a thread accesses a synchronized instance of an object, can other threads access other synchronized methods?

Other threads can enter if other methods are not synchronized.

So to open a thread-safe object, make sure that every method is thread-safe.

Optimistic lock and pessimistic lock understanding and how to achieve, what is the way to achieve?

Pessimistic locking: Always assume the worst, every time you go to get the data you think someone else will change it, so every time you get the data you lock it, so that someone else tries to get the data it will block until it gets the lock. Traditional relational database inside used a lot of this locking mechanism, such as row lock, table lock, read lock, write lock, etc., are in the operation before the first lock. Another example is the implementation of the synchronized keyword in Java.

Optimistic lock: as the name implies, is very optimistic, every time to get the data, I think others will not modify, so I will not lock, but when updating, I will judge whether others have to update the data during this period, you can use the version number and other mechanisms. Optimistic locks are suitable for multi-read applications to improve throughput. Optimistic locks are provided by databases similar to write_condition. In Java. Java util. Concurrent. Atomic package this atomic variable classes is to use the optimistic locking a way of implementation of CAS.

Optimistic locking can be implemented as follows:

1. Use the version identifier to determine whether the data read is consistent with the data submitted. Modify the version id after submission, and discard and try again if it is inconsistent.

2. Compare and Swap in Java is CAS. When multiple threads try to use CAS to update the same variable at the same time, only one thread can update the value of the variable, while all other threads fail. The CAS operation contains three operands — the memory location to be read and written to (V), the expected original value to be compared (A), and the new value to be written to (B). If the value of memory location V matches the expected original value A, the processor automatically updates that location value to the new value B. Otherwise the processor does nothing.

CAS faults:

1. ABA problems:

Let’s say one thread fetches A from location V, and two thread two fetches A from location V, and two does something to change it to location B, and then two changes the data from location V to location A, Thread one performs the CAS operation and finds that A is still in memory. Then thread ONE succeeds. Although the CAS operation for thread one was successful, there may be a lurking problem. Since Java1.5, the JDK atomic package has provided a class AtomicStampedReference to address ABA issues.

2. Long cycle time and high cost:

In the case of serious resource competition (serious thread conflict), CAS has a high probability of spin, which wastes more CPU resources and is less efficient than synchronized.

3. Atomic operations that only one shared variable can be guaranteed:

When performing operations on a shared variable, we can loop CAS to ensure atomic operations, but when performing operations on multiple shared variables, the loop CAS cannot guarantee atomic operations, so we can use locks.

What is the difference between SynchronizedMap and ConcurrentHashMap?

SynchronizedMap locks the entire table at a time to ensure thread-safety, so only one thread can call the map at a time.

ConcurrentHashMap uses segmented locking to ensure performance in multiple threads.

ConcurrentHashMap locks one bucket at a time. ConcurrentHashMap Divides the hash table into 16 buckets by default. Common operations such as GET, PUT, and remove lock only the buckets that are currently used.

As a result, a single thread can now be entered by 16 writers at the same time, and the concurrency improvement is noticeable.

ConcurrentHashMap also uses a different iteration approach. In this iteration, the collection is no longer thrown when the iterator has been created and then changed

ConcurrentModificationException, instead of changing the new new data which does not affect the original data, the iterator is completed and then turn the head pointer is replaced by the new data, so that the iterator threads can use old data, The writer thread can also make changes concurrently.

37. What application scenarios can CopyOnWriteArrayList be used for?

CopyOnWriteArrayList lock containers (exemption) when more than one iterator is one of the advantages of traverse and modify the list at the same time, ConcurrentModificationException. In CopyOnWriteArrayList, writing causes a copy of the entire underlying array to be created, while the source array is left in place so that reads can be safely performed while the copied array is modified.

If the contents of the original array are too large, it may cause young GC or full GC. If the contents of the original array are too large, it will consume memory.

2, can not be used for real-time read scenarios, such as copying array, new elements take time, so call a set operation, read data may be old, although CopyOnWriteArrayList can achieve the final consistency, but still can not meet the real-time requirements;

Ideas revealed by CopyOnWriteArrayList

1. Separate reading and writing, and separate reading and writing

2. Final consistency

3. Use the idea of creating additional space to solve concurrency conflicts

What is thread safety? Are servlets thread-safe?

Thread safety is a programming term. When a function or library is called in a multi-threaded environment, it can correctly handle the shared variables between multiple threads, so that the program functions can be completed correctly.

Servlets are not thread-safe. Servlets are single-instance multithreaded, and when multiple threads access the same method at the same time, there is no guarantee of thread-safe sharing of variables.

Struts2 actions are multi-instance, multi-threaded and thread-safe. Each request is assigned a new action and destroyed when completed.

Is SpringMVC’s Controller thread safe? No, it’s a servlet-like process.

Struts2 has the advantage of not having to worry about thread safety; Servlets and SpringMVC need to consider thread safety, but the performance can be improved by not having to deal with too many GCS and using ThreadLocal to handle multithreading issues.

39. What is volatile for? Can you explain in one sentence how volatile is used?

Volatile ensures memory visibility and disallows instruction reordering.

Volatile is used for a single operation (read or write) in a multithreaded environment.

40. Why is code reordered?

When executing a program, processors and compilers often reorder instructions to provide performance. However, reordering is not optional. It requires that the following two conditions be met:

In a single thread environment cannot change the results of the program running;

Data dependencies cannot be reordered

Note that reordering does not affect the execution results of a single-threaded environment, but does break the execution semantics of multithreading.

41, What is the difference between wait and sleep in Java?

The big difference is that while wait releases the lock, sleep holds it all the time. Wait is usually used for interthread interactions, and sleep is usually used to pause execution.

Using Java to implement blocking queues

43. What happens when an exception occurs while a thread is running?

The thread will stop execution if the exception is not caught. Thread. UncaughtExceptionHandler is used for uncaught exception handling Thread sudden interruption of an embedded interface. When an uncaught exception Thread will break off when the JVM can use Thread. GetUncaughtExceptionHandler () to query the Thread UncaughtExceptionHandler Thread and abnormal passed as a parameter to the handler UncaughtException () method.

44. How do I share data between two threads?

This is achieved by sharing variables between two threads.

In general, shared variables require that the variables themselves be thread-safe, and then that compound operations on shared variables be thread-safe when used in threads.

45. What is the difference between notify and notifyAll in Java?

Notify () doesn’t wake up a specific thread, so it’s only useful if one thread is waiting. NotifyAll (), on the other hand, awakens all threads and allows them to compete for locks, ensuring that at least one thread can continue running.

46. Why don’t Wait, notify, and notifyAll belong to Thread?

One obvious reason is that JAVA provides locks at the object level rather than the thread level. Each object has a lock, which is acquired by the thread. Because wait, notify, and notifyAll are lock-level operations, we define them in the Object class because locks belong to objects.

47. What are ThreadLocal variables?

ThreadLocal is a special kind of variable in Java. A ThreadLocal for each thread means that each thread has its own independent variable, eliminating the contention condition completely. It’s a good way to get thread-safe for creating expensive objects. For example, you can use ThreadLocal to make SimpleDateFormat thread-safe. Because that class is expensive to create and requires a different instance to be created each time it’s called, it’s not worth using it locally. It would be much more efficient to provide each thread with its own unique copy of variables. First, reuse reduces the number of expensive objects to create. Second, you get thread safety without using costly synchronization or immutability.

What is the difference between the interrupted and isInterrupted methods in Java?

interrupt

The interrupt method is used to interrupt a thread. The state of the thread calling this method is to be set to “interrupted”.

Note: a thread interrupt simply sets the interrupt status bit of the thread and does not stop the thread. It is up to the user to monitor the thread state and do the processing. Methods that support thread interrupts (that is, methods that throw interruptedException after a thread interrupts) monitor the interrupted status of a thread and throw an interrupt exception once the thread’s interrupted status is set to “interrupted.”

interrupted

Query the interrupted state of the current thread and clear the original state. If a thread is interrupted, the first call to interrupted returns true and the second and subsequent calls false.

isInterrupted

Simply query the interrupt status of the current thread

49. Why are wait and notify called in a synchronized block?

Java API forced to do so, if you don’t do this, your code will be thrown IllegalMonitorStateException anomalies. Another reason is to avoid race conditions between WAIT and notify.

50. Why should you check the wait condition in a loop?

Threads in the wait state may receive error alerts and pseudo-awakenings, and if the wait condition is not checked in the loop, the program will exit without meeting the end condition.

What is the difference between synchronous and concurrent collections in Java?

Both synchronous and concurrent collections provide suitable thread-safe collections for multithreading and concurrency, although concurrent collections are more extensible. Prior to Java1.5, programmers had only synchronous collections to use and contention was caused when multiple threads were running concurrently, hindering system scalability. Java5 introduces concurrent collections like ConcurrentHashMap, which not only provide thread safety but also improve scalability with modern techniques such as lock separation and internal partitioning.

What is a thread pool? Why use it?

Threads are expensive to create in terms of resources and time, the response time can be slow if the task comes in, and the number of threads a process can create is limited. To avoid these problems, a number of threads are created at program startup to respond to processing. These threads are called thread pools, and the threads inside are called worker threads. Starting with JDK1.5, the Java API provides an Executor framework that allows you to create different thread pools.

How do I check if a thread has a lock?

There is a method called holdsLock() in java.lang.Thread that returns true if and only if the current Thread has a lock on a specific object.

54. How do you get a thread stack in Java?

kill -3 [java pid]

It will not be output at the current terminal, it will be output to the code execution or specified. For example, kill -3

Tomcat PID, output stack to log directory.

Jstack [java pid]

This is relatively simple and can be displayed on the current terminal or redirected to a specified file.

– JvisualVM: Thread Dump

Do not explain, open JvisualVM, are interface operations, the process is very simple.

55, Which parameter in the JVM is used to control the thread stack to be small?

-Xss Stack size for each thread

56. What is the yield method for Thread?

Causes the current thread to change from the executing (running) state to the executable (ready) state.

The current thread is ready, so which thread will go from ready to execution next? It could be the current thread, or it could be another thread, depending on the system allocation.

What is the concurrency of ConcurrentHashMap in Java?

ConcurrentHashMap Divides the actual map into parts to achieve scalability and thread-safety. This partition is obtained using concurrency, which is an optional argument to the ConcurrentHashMap class constructor and defaults to 16 to avoid contention in multithreaded cases.

After JDK8, it abandons the concept of Segment and instead enables a completely new way to implement it, using the CAS algorithm. At the same time added more auxiliary variables to improve concurrency, the specific content or check the source code.

What is Semaphore in Java?

Semaphore in Java is a new synchronization class that is a count signal. Conceptually, semaphores maintain a set of permissions. If necessary, each acquire() is blocked until the license is available, and then the license is obtained. Each release() adds a license, possibly freeing a blocking acquirer. However, instead of using actual license objects, Semaphore only counts the number of licenses available and acts accordingly. Semaphores are often used in multithreaded code, such as database connection pooling.

59, What is the difference between submit() and execute() methods in Java thread pools?

Both methods can submit tasks to a thread pool, and the execute() method returns void, which is defined in the Executor interface.

The Submit () method returns a Future object that holds the results, which is defined in the ExecutorService interface and extends the Executor interface, Other types of thread pool as ThreadPoolExecutor and ScheduledThreadPoolExecutor has these methods.

60. What are blocking methods?

A blocking method means that the program waits for the method to complete and does nothing else. The ServerSocket Accept () method waits for the client to connect. In this case, blocking means that the current thread is suspended until the result of the call is returned and will not return until the result is returned. In addition, there are asynchronous and non-blocking methods that return before the task is complete.





What is ReadWriteLock in Java?

Read/write locking is the result of lock separation technology used to improve the performance of concurrent programs.

62. What is the difference between volatile variables and atomic variables?

Volatile variables ensure antecedence, that is, that writes occur before subsequent reads, but they do not guarantee atomicity. For example, if the count variable is volatile, the count++ operation is not atomic.

The AtomicInteger class provides an atomic method to make this operation atomic. For example, the getAndIncrement() method increments the current value atomically, and other data types and reference variables can perform similar operations.

63. Can I call the run () method of Thread directly?

B: Sure. But if we call Thread’s run() method, it will behave like normal methods and execute in the current Thread. To execute our code in a new Thread, we must use the thread.start () method.

64. How do I suspend a running thread for a period of time?

We can use the Thread class’s Sleep() method to suspend a Thread for a while. Note that this does not terminate the thread; once it is awakened from sleep, the thread’s state will be changed to Runnable and it will be executed according to thread scheduling.

What is your understanding of thread priority?

Each thread has priority. Generally speaking, threads with higher priority have priority at run time, but this depends on the implementation of thread scheduling, which is OS dependent. We can define the priority of a thread, but this does not guarantee that a higher-priority thread will execute before a lower-priority thread. Thread priority is an int variable (1-10), with 1 representing the lowest priority and 10 representing the highest priority.

Java thread priority scheduling is delegated to the operating system, so it depends on the operating system priority. You do not need to set thread priority unless it is necessary.

66. What are Thread schedulers and Time Slicing?

The Thread scheduler is an operating system service that allocates CPU time to Runnable threads. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Again, thread scheduling is not controlled by the Java VIRTUAL Machine, so it is better for the application to control it (i.e., don’t make your program dependent on thread priority).

Time sharding is the process of allocating available CPU time to available Runnable threads. CPU time can be allocated based on thread priority or the amount of time a thread waits.

67. How do you ensure that the thread on which the main() method is located is the last thread to terminate a Java program?

We can use the Join () method of the Thread class to ensure that all threads created by the program end before the main() method exits.

How do threads communicate with each other?

When threads can share resources, inter-thread communication is an important means of coordinating them. The wait()\notify()\notifyAll() method of the Object class can be used to communicate the status of locks on resources between threads.

69. Why are the methods wait(), notify(), and notifyAll() defined in Object?

Each Java object has a lock (monitor, which can also be a monitor), and methods such as wait(), notify() are used to wait for the lock of the object or to notify other threads that the monitor of the object is available. There are no locks and synchronizers available to any object in a Java thread. That’s why these methods are part of the Object class, so that every Java class has basic methods for interthread communication.

70. Why must wait(), notify(), and notifyAll () be called in synchronized methods or blocks?

When a thread wants to call wait() on an object, the thread must own the lock on the object. It then releases the lock and waits until another thread calls notify() on the object. Similarly, when a thread needs to call notify() on an object, it releases the lock on that object so that other waiting threads can acquire the lock. Because all of these methods require the thread to hold the lock on the object and thus can only be implemented through synchronization, they can only be called in synchronized methods or synchronized blocks.

71. Why are Thread sleep() and yield () static?

The Sleep () and yield() methods of the Thread class will run on the Thread currently executing. So it doesn’t make sense to call these methods on other threads that are in the wait state. That’s why these methods are static. They work in the currently executing thread and prevent programmers from making the mistake of thinking they can be called in another non-running thread.

How to ensure thread safety?

There are many ways to ensure thread-safety in Java — synchronization, using atomic concurrent classes, implementing concurrent locking, using the volatile keyword, using immutable and thread-safe classes.

Which is a better choice, synchronous method or synchronous block?

A synchronized block is a better choice because it doesn’t lock the whole object (although you can make it lock the whole object). Synchronized methods lock the entire object, even if there are multiple unrelated synchronized blocks in the class, which usually causes them to stop executing and wait to acquire the lock on the object.

Synchronized blocks are more consistent with the principle of open calls, locking objects only when the code block needs to be locked, thus avoiding deadlocks from the side.

How do I create a daemon thread?

Using Thread class setDaemon (true) method, a Thread can be set to daemon Thread, it is important to note that need to be in front of the call start () method calls this method, otherwise will be thrown IllegalThreadStateException anomalies.

What is the Java Timer class? How do I create a task with a specific time interval?

Java.util. Timer is a utility class that can be used to schedule a thread to execute at a specific time in the future. The Timer class can be used to schedule one-off or periodic tasks.

Java.util. TimerTask is an abstract class that implements the Runnable interface. We need to inherit this class to create our own scheduled task and schedule its execution using a Timer.

The last

2019 common Java interview questions summed up a nearly 500 page PDF document, welcome to follow my official account: Programmer chasing wind, receive these sorted materials!


If you like the article, remember to pay attention to me. Thank you for your support!