Thread article

1. What are threads?

Thread is the smallest unit that the operating system can schedule operations. It is contained in the process and is the actual operating unit in the process. It allows programmers to do multiprocessor programming, and you can use multithreading to speed up computationally intensive tasks. For example, if it takes 100 milliseconds for one thread to complete a task, it takes 10 threads to complete the task in 10 milliseconds.

2. What is the difference between threads and processes?

A process is a self-contained runtime environment that can be considered a program or an application. A thread is a task that is executed in a process. Threads are a subset of processes, and a process can have many threads, each performing different tasks in parallel. Different processes use different memory space, and all threads share the same memory space. Not to be confused with stack memory, each thread has a separate stack memory to store local data.

3. How to implement threads in Java?

There are two ways to create a Thread: implement the Runnable interface and pass it to the Thread constructor to create a Thread object. The other is to inherit the Thread class directly.

4. Runnable or Thread?

We all know that we can implement threads by inheriting the Thread class or by calling the Runnable interface. The question is, which is better? When is it used? This question is easy to answer if you know that Java does not support multiple inheritance of classes, but allows you to call multiple interfaces. So if you want to inherit from another class, of course call the Runnable interface. More details can be found here.

5. What is the difference between the start() and run() methods in Thread?

The start() method is used to start the newly created thread and make it runnable. When you call the run() method, it will only be called in the original thread. No new thread will be started, so the start() method will start a new thread. If we call Thread’s run() method, it will behave like normal methods, running the run() method directly. To execute our code in a new Thread, we must use the thread.start () method.

6. What is the difference between Runnable and Callable in Java?

Runnable and Callable both represent tasks that are to be executed in different threads. Runnable has been available since JDK1.0, Callable was added in JDK1.5. The main difference is that Callable’s Call () method can return values and throw exceptions, while Runnable’s Run () method does not. Callable can return a Future object loaded with computed results.

7. What is the difference between CyclicBarrier and CountDownLatch in Java?

Both CyclicBarrier and CountDownLatch can be used to make a group of threads wait for other threads.

Unlike CyclicBarrier, CountdownLatch cannot be reused.

8. What is the Java memory model?

The Java memory model specifies and guides the deterministic behavior of Java programs across memory architectures, cpus, and operating systems. This is especially important in the case of multithreading. The Java memory model provides a guarantee that changes made to one thread can be seen by other threads, and that they are antecedent. This relationship defines rules that allow programmers to think more clearly about concurrent programming. Like, having sex first ensures that.

  • Code in a thread can be executed in sequence, which is called the program order rule.
  • For the same lock, one unlock operation must take place after another lock operation, also known as pipe lock rule.
  • A previous write to volatile before a subsequent read from volatile. Also known as a volatile variable rule.
  • Any operation within a thread must be followed by a start() call from that thread, also known as the thread start rule.
  • All operations of a thread are terminated before the thread terminates.
  • Finalization of an object must occur after the object is constructed. Also called object finalization rule.
  • Can be delivered

9. What is thread safety? Is Vector a thread-safe class?

If your code is in a process that has multiple threads running at the same time, those threads may be running the code at the same time. If the result of each run is the same as the result of a single thread run, and the values of other variables are the same as expected, it is thread-safe. The same instance object of a thread-safe counter class can be used by multiple threads without miscalculation. Obviously you can split collection classes into two groups, thread-safe and non-thread-safe. Vector is thread-safe using a synchronous approach, whereas ArrayList, like it, is not thread-safe.

10. What are race conditions in Java?

In most practical multithreaded applications, two or more threads need to share access to the same data. What happens if thread I accesses the same object, and each thread calls a method that modifies the state of that object? Imagine threads stepping on each other’s toes. Depending on the order in which the thread accesses the data, you can have corrupted objects. Such conditions are often referred to as competition conditions.

11. How to stop a thread in Java?

Java provides a rich API but not one for stopping threads. JDK 1.0 originally had some control methods like stop(), suspend(), and resume(), but due to potential deadlock threats. They were therefore deprecated in subsequent JDK versions, after which the Designers of the Java API did not provide a compatible and thread-safe way to stop a thread. The thread terminates automatically when the run() or call() methods are complete. To terminate a thread manually, use volatile Boolean variables to exit the run() loop or cancel the task to interrupt the thread.

12. 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 uncaught exception passed as a parameter to the handler The Exception() method.

What is the difference between notify and notifyAll in Java?

This is another tricky problem, because multiple threads can wait for a single monitor lock, and the Java API designers provide ways to notify them when the wait condition changes, but these methods are not fully implemented. 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.

14. Why are wait, notify, and notifyAll not in the Thread class?

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. It makes sense to call wait() on an object if the thread needs to wait for some lock. If the wait() method is defined in the Thread class, it is not obvious which lock the Thread is waiting on. Simply put, because wait, notify, and notifyAll are lock-level operations, we define them in the Object class because locks belong to objects.

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

16. What is FutureTask?

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.

17. What is the difference between interrupted and isInterruptedd in Java?

The main difference between interrupted() and isInterrupted() is that the former clears the interrupted state while the latter does not. The interrupt mechanism for Java multithreading is implemented with an internal identifier. Calling thread.interrupt () to interrupt a Thread sets the interrupt identifier to true. The interrupted status is cleared when the interrupted Thread calls the static method thread.interrupted () to check the interrupted status. The non-static isInterrupted() method is used to query the interrupted status of other threads without changing the interrupt status flag. Simply put, any method that throws InterruptedException clears the interrupted status. However, the interrupt state of one thread can be changed by other threads calling interrupts.

18. Why are wait and notify called in synchronous 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. If you don’t do this, the code will be thrown IllegalMonitorStateException anomalies.

19. 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 the difference between a heap and a stack in Java?

Why is this problem classified as a multi-threaded and simultaneous problem? Because the stack is an area of memory that is closely related to threads. Each thread has its own stack memory for storing local variables, method parameters, and stack calls. Variables stored in one thread are not visible to other threads. The heap is a common area of memory shared by all threads. Objects are created in the heap, and to improve efficiency a thread will take a cache from the heap to its stack. If multiple threads use this variable, it can cause problems. Volatile variables are useful, requiring the thread to read the value of the variable from main memory.

21. How to write code to solve producer-consumer problems?

In reality, many threading problems you solve are producer-consumer models, where one thread produces tasks for other threads to consume, and you have to know how to communicate between threads to solve this problem. The lower-level approach is to use wait and notify to solve this problem, while the better approach is to use Semaphore or BlockingQueue to implement the producer-consumer model.

22. How do I avoid deadlocks?

Deadlocks in Java multithreading

A deadlock is a phenomenon in which two or more processes are waiting for each other during execution because they are competing for resources and cannot proceed without external forces. This is a serious problem because deadlocks can cause your program to hang and fail to complete its task. The following four conditions must be met for a deadlock to occur:

  • Mutually exclusive condition: a resource can only be used by one process at a time.
  • Request and hold conditions: when a process is blocked by requesting resources, it holds on to acquired resources.
  • Non-dispossession condition: a process cannot forcibly take away a resource it has acquired until it is used up.
  • Circular waiting condition: a circular waiting resource relationship is formed between several processes.

The simplest way to avoid deadlocks is to prevent cyclic waiting conditions, set flags and sorts for all resources in the system, and specify that all processes must apply for resources in a certain order (ascending or descending) to avoid deadlocks.

23. What is the difference between live locks and deadlocks in Java?

A live lock is similar to a deadlock, except that the state of the thread or process in a live lock is constantly changing. A live lock can be considered a special kind of hunger. A realistic example of a live lock is when two people encounter each other in a narrow hallway. Both people try to avoid each other so that they can pass each other, but because they avoid each other in the same direction, no one can get through the hallway. In short, the main difference between a live lock and a deadlock is that the state of the former process can change but execution cannot continue.

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

25. Which parameter in the JVM is used to control the thread stack to be small

The problem is simple, the -xss argument is used to control the stack size of the thread. You can see the JVM configuration list to learn more about this parameter.

26. What is the difference between Synchronized and ReentrantLock in Java?

For a long time Java could only implement mutual exclusion with the synchronized keyword, which has some disadvantages. For example, you can’t extend methods or block boundaries outside the lock, and you can’t cancel when trying to acquire the lock. Java 5 addresses these issues by providing more sophisticated controls through the Lock interface. The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized, and is also extensible.

27. What is the use of yield in Thread?

The yield method suspends the currently executing thread object to allow other threads of the same priority to execute. It is a static method and only guarantees that the current thread will give up CPU usage, but does not guarantee that other threads will be able to use CPU usage. A thread that performs yield() may be executed immediately after entering the pause state.

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

29. If the thread pool queue is full when you submit the task. What happens when it happens?

This is a tricky question, and many programmers would assume that the task would block until the thread pool queue became empty. In fact if a task scheduler can’t ThreadPoolExecutor ‘s submit () method will throw a RejectedExecutionException anomalies.

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

Both methods can submit tasks to a thread pool. The execute() method returns void, which is defined in the Executor interface, and the Submit () method returns a Future object that holds the results of the computation, which is defined in the ExecutorService interface. It expanded the Executor interface, other thread pool class like ThreadPoolExecutor and ScheduledThreadPoolExecutor has these methods.

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

32. What is ReadWriteLock in Java?

In general, read-write locks are the result of lock separation techniques used to improve the performance of concurrent programs. ReadWriteLock in Java is a new interface in Java 5. One ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writes. A read lock can be held by multiple reader threads without a writer thread. Write locks are exclusive, and you can implement this rule using ReentrantReadWriteLock in the JDK, which supports up to 65535 write and 65535 read locks.

33. What is the double check for singleton mode?

This question is often asked in Java interviews, but interviewers are only 50% satisfied with the answer. Half of you couldn’t write double-check and half of you couldn’t tell me what it was and how Java1.5 fixed it. It is actually an old method for creating thread-safe singletons, which tried to optimize performance with a single lock when singletons were first created, but failed in JDK1.4 because it was too complex.

34. How to create a thread-safe Singleton in Java?

This is a follow-up to the above question. If you don’t like double-checking and the interviewer asks for an alternative way to create a Singleton class, you can either use the JVM’s classloading and static variable initialization features to create Singleton instances, or use enumerated types to create Singleton instances.

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.

36. How do I create daemons?

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.

37. Which is a better choice, synchronization method or synchronization 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.

38. What is the lock upgrade process?

Lock upgrade sequence

  • unlocked
  • Biased locking
  • Lightweight lock
  • Heavyweight lock

First is unlocked, determine whether or not to lock, lock, upgraded to a biased locking, biased locking means if one thread lock, you don’t have to request again lock, if there are other threads to access, just upgraded to a lightweight lock, by CAS to acquire the lock, if the CAS fails, if not successful after spin to a certain number of times is upgraded to a heavy lock. (The thread should be suspended if the spin exceeds the limit (the default is 10 unsuccessful attempts to acquire the lock)

! [Java interview questions summary – threads (it is worth collecting)] (https://p6-tt.byteimg.com/origin/pgc-image/9d2f9c64be484f2581db20bf2366eb76?from=pc)
! [Java interview questions summary – threads (it is worth collecting)] (https://p6-tt.byteimg.com/origin/pgc-image/c3098e0c52594c69b9eed0858ad9b8e2?from=pc)

39. What is volatile?

Volatile is a lightweight synchronization mechanism provided by the Java Virtual machine

1. Ensure visibility

2. Atomicity is not guaranteed

3. Forbid instruction rearrangement (orderliness)

(1) Why not support atomicity?

Because there are four steps to changing volatile variables:

  1. Read volatile variables into local memory.
  2. Modifying variable values
  3. Write the value back to main memory.
  4. Insert a memory barrier, the Lock instruction, to make it visible to other threads.

Because the first three steps are not thread-safe, there is no guarantee that the value and write back have not been modified by other threads. Atomicity is guaranteed by locking.

(2) If atomicity is guaranteed?

1. Use synchronized

2. Use the Atomic class

(3) Why are Atomic classes guaranteed to be Atomic?

Because CAS is used.

CAS is: compare and swap

Boolean AtomicInteger.com pareAndSwap (expectations, update value)

Is a CPU concurrency primitive.

Using the Unsafe class, most methods use the native modifier.

The Unsafe class retrieves data based on memory offset addresses.

! [Java interview questions summary – threads (it is worth collecting)] (https://p6-tt.byteimg.com/origin/pgc-image/592b93a9a6fe4b56aff7461b857ac060?from=pc)

(4) What about ABA of AtomicInteger?

The problem with ABA is that it was A in main memory and then another thread changed it to B and changed it back to A, and the first thread came back and still A thought there was no change, but there was A change.

How to solve THE ABA problem?

AtomicStampedReference Adds the version number and determines the version number.

39. What kinds of thread pools can be created?

  1. Executors. NewFixedThreadPool (int) : fixed the thread pool size.
  2. Executors. NewSingleThreadExecutor () : the singleton thread pool
  3. Executors. NewChachedThreadPool () : the expandable cached thread pool.

40. What is the difference between execute and submit?

Execute and Submit are both thread pool methods. Execute can only submit tasks of the Runnable type, while Submit can submit tasks of the Runnable type and Callable type.

Execute will directly throw the exception during the task execution, submit will eat the exception, through the Future get method to re-throw the exception during the task execution.

Execute belongs to Executor,submit belongs to ExecutorService. The implementation class ThreadPoolExecutor overwrites the Execute method and the abstract class AbstractExecutorService overwrites the Submit method.

41. What are the ThreadPoolExcutor parameters?

! [Java interview questions summary – threads (it is worth collecting)] (https://p1-tt.byteimg.com/origin/pgc-image/1227192360214161bee5504088429433?from=pc)

42. What is the underlying principle of thread pools?

! [Java interview questions summary – threads (it is worth collecting)] (https://p3-tt.byteimg.com/origin/pgc-image/cef22aa22bc34f988d5166bcc3959f11?from=pc)
  1. When the execute() method is called to add a request task, the thread pool makes the following decisions:
  2. If the current corePoolSize is not full, a thread is created to run the task.
  3. If corePoolSize is full, the thread is put into the blocking queue.
  4. If the blocking queue is full and smaller than maxmumPoolSize, a non-core thread is created to run the task.
  5. If the blocking queue is full and maxmumPoolSize is full, the rejection policy is used to execute.
  6. When a task completes, the next one is fetched from the queue to execute the task.
  7. When a thread is idle for more than a certain amount of time, it is stopped, and when all thread tasks are completed, the thread pool shrinks to corePoolSize.

43. What are the four denial policies for thread pools?

  1. AbortPolicy (default) : direct selling RejectedExecutionException exception to prevent normal operation of system.
  2. CallerRunsPolicy: The task is rolled back to the caller without dropping the task or throwing an exception.
  3. DiscardOldestPolicy: Discards the longest waiting task in the queue and adds the current task to the queue.
  4. DiscardPolicy: Discards the task without processing it or throwing an exception.

44. Why not allow the Executors to create a thread pool?

  1. FixedThreadPool and SingleThreadPool:

The allowed queue length is integer. MAX_VALUE, which may accumulate a large number of requests and result in OOM.

  1. CachedThreadPool and ScheduledThreadPool:

The number of threads allowed to be created is integer. MAX_VALUE, which may pile up a large number of threads, resulting in OOM.

45. How do I create a custom thread pool?

public static void main(String[] args) { ExecutorService theadPool = new ThreadPoolExecutor( 2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); // Default reject policy try {for (int I = 0; i < 30; I++) {theadpool.execute (() -> system.out.println (thread.currentthread ().getname () +" ")); } }catch (Exception e) { e.printStackTrace(); }finally { theadPool.shutdown(); }}Copy the code

46. What are blocking queues?

  • ArrayBlockingQueue: ArrayBlockingQueue is a bounded blocking queue based on an array structure that sorts data in FIFO (first-in, first-out) order.
  • LinkedBlockingQueue: A linked list-based bounded blocking queue that sorts elements in FIFO and has a higher throughput than ArrayBlockingQueue. Default size is int Max (because read and write can be done at the same time, not the same lock)
  • SynchroniousQueue: A queue that does not store elements until each insert is removed by another thread. Otherwise it will always be blocked. Throughput is higher than LinkedBlockingQueue.

47. Why do I need BlockingQueue?

The advantage is that we no longer have to worry about when to block and when to wake up threads, because the blocking queue will automatically block adding threads when they are full. Block the fetch thread when empty. Once the blocking queue is no longer full, the add thread is automatically woken up to add.

48. What are the BlockingQueue core methods?

! [Java interview questions summary – threads (it is worth collecting)] (https://p3-tt.byteimg.com/origin/pgc-image/6e14bb86278342ac85eb4596ad8977ca?from=pc)
! [Java interview questions summary – threads (it is worth collecting)] (https://p1-tt.byteimg.com/origin/pgc-image/637497a1e89f4a8c9735cec5f0ca529a?from=pc)

49. How to avoid false awakenings?

Use while, not if. Because the while resets the condition after it wakes up.

50. What’s the difference between Lock and synchronized?

  1. Synchronized is the JVM layer, and the bottom layer is accomplished through monitor objects. Wait /notify and other methods rely on monitor objects. And monitorexit. This includes both normal and abnormal exits. Lock is an API level Lock.
  2. Synchronized does not require manual lock release. Lock requires manual lock release. Otherwise, a deadlock may occur.
  3. Synchronized cannot be broken. Lock can be set to the timeout method trylock() and interrupt() can be broken.
  4. Synchronized is an unfair lock. A lock can be a fair or unfair lock.
  5. Lock can precisely wake up a thread, whereas synchronized can only wake up all or randomly.