Today to share with you the Java concurrent programming interview battery.

Hope that through this kind of rapid-fire way, so that we better absorb knowledge, but also in the interview frequency is very high.

God’s perspective

Let’s cut to the chase.

Start firing

1. What is a thread?

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.

What is the difference between a thread and a process?

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.

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.

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.

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. For example, 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

It is highly recommended that you read Chapter 16 of Concurrent Programming practices in Java to deepen your understanding of the Java memory model.

What is a volatile variable in Java?

Volatile is a special modifier that can only be used by member variables. In the absence of synchronous classes in Java concurrent programs, multithreading operations on member variables are transparent to other threads. Volatile variables guarantee that the next read will occur after the previous write. The thread reads the variable directly from memory and does not cache it. This ensures that the variables read by the thread are consistent with those in memory.

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.

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.

How do you 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.

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

How do I share data between two threads?

You can do this by sharing objects, or by using concurrent data structures such as blocking queues. This tutorial, Java Inter-Thread Communication, which involves sharing objects between two threads, implements the producer-consumer model with wait and notify methods.

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

16. Why aren’t Wait, notify, and notifyAll methods in 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. 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.

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

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

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

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

21. 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. Therefore, when a wait thread wakes up, its original wait state cannot be considered to be still valid; it may change between the time after the notify() call and the time before the wait thread wakes up. This is why it works better to use wait() in a loop, and you can try it out by creating templates in Eclipse that call WAIT and notify. If you want to learn more about this topic, I recommend reading the threads and Synchronization chapter in Effective Java.

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

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

24. 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. Such as a single thread pool, one task at a time; A fixed number of thread pools or a cache thread pool (an extensible thread pool suitable for a program with many short-lived tasks).

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

26. How to 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.

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

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.

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

For different operating systems, there are several ways to get the thread stack for a Java process. When you fetch the thread stack, the JVM stores the state of all threads to a log file or prints it to the console. On Windows you can use Ctrl + Break to get the thread stack, on Linux you can use kill -3. You can also use the jStack tool, which operates on thread ids, and you can use the JPS tool to find ids.

30. Which parameter in the JVM is used to control the thread stack size

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.

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

32, There are three threads T1, T2, T3, how to ensure that they execute in sequence (ensure that main() thread is the last thread to terminate the Java program)?

In multithreading, there are several ways to get threads to execute in a particular order. You can use the join() method of the thread class to start another thread in one thread, and another thread will finish the thread and continue executing. To ensure the order of the three threads you should start the last one first (T3 calls T2, T2 calls T1) so that T1 finishes first and T3 finishes last.

33. What is the yield method for 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. Click here for more on yield methods.

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

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. More details can be found here.

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

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. More details can be found here.

38. 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. More details can be found here.

39. What do you understand about thread priorities?

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.

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. 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. Thread scheduling is not controlled by the Java VIRTUAL Machine, so it is better for the application to control it (that is, don’t make your program dependent on thread priority).

41. What is context-switching in multithreading?

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.

42, How to create Immutable objects in Java?

Immutable objects can be shared without synchronization, reducing the synchronization overhead when accessing the object concurrently. To create immutable classes, in order to achieve the following several steps: by the method of tectonic initialize all the members, the variables don’t provide a setter method, all the members of the statement for the private, so it does not allow direct access to these members, in the getter method, do not return to the object itself directly, but a cloned objects, and return a copy of the object.

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.

What is the busy loop in multithreading?

A busy loop is one in which a programmer uses a loop to make a thread wait. Unlike the traditional methods wait(), sleep(), or yield(), which give up CPU control, a busy loop does not give up CPU. It simply runs an empty loop. The purpose of this is to preserve the CPU cache, and in a multi-core system, a waiting thread may be running in another kernel when it wakes up, thus rebuilding the cache. It can be used to avoid rebuilding the cache and reduce waiting time for rebuilding.

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

That’s an interesting question. First, volatile and atomic variables look very similar, but they don’t function the same way. 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.

What happens if a thread in a synchronized block throws an exception?

This question confuses many Java programmers, but if you can think of a clue as to whether the lock is released or not to answer it, you might get it right. The thread inside the finally block will release the lock regardless of whether your synchronized block exits normally or abnormally, so we prefer synchronized blocks to locking interfaces because they don’t have to expend effort to release the lock.

47, What is the double check of 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.

48, How to create 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.

Write down 3 best practices for multithreading that you follow

Here are three best practices that most Java programmers should follow:

  • Give your threads meaningful names.

This makes it easy to find bugs or track them. OrderProcessor QuoteProcessor or TradeProcessor the name than the Thread – 1. The Thread – 2 and Thread – 3 better, give a Thread a associated with it to complete the task name, All major frameworks, even the JDK, follow this best practice.

  • Avoid locking and narrowing the scope of synchronization

Locking is expensive and context switching is time and space consuming, so try minimizing synchronization and locking to reduce critical areas. So I prefer synchronized blocks to synchronized methods, which give me absolute control over the lock.

  • Use synchronous classes more often and less oftenwaitandnotify

First, synchronization classes such as CountDownLatch, Semaphore,CyclicBarrier and Sanodomain simplify encoding, while wait and notify are difficult to control complex control flows. Second, these classes are written and maintained by the best companies and will continue to be refined and refined in subsequent JDKS. With these higher-level synchronization tools, your programs can be optimized without much effort.

  • Use more concurrent collections and less synchronous collections

Another best practice that is easy to follow and hugely beneficial is that concurrent collections are more scalable than synchronous collections, so it is better to use concurrent collections when programming concurrently. The next time you need to use a Map, the first thing you should think about is using ConcurrentHashMap.

How do I force a thread to start?

This problem is similar to how to enforce Java garbage collection. There is no known method, although you can use System.gc() to do garbage collection, but success is not guaranteed. There is no way to force a thread to start in Java, it is controlled by the thread scheduler and Java does not publish the relevant API.

51, What is the Fork Join framework in Java?

The Fork Join framework is an efficient tool emerging in JDK7 that allows Java developers to take full advantage of multiple processors on modern servers. It is designed for those that can be recursively divided into many submodules, with the goal of using all available processing power to improve the performance of the program. f

A big advantage of the Fork Join framework is that it uses a work-stealing algorithm, so worker threads that can do more can steal tasks from other threads to execute them.

What is the difference between calling wait() and sleep() in Java multithreading?

Both Wait and sleep in Java programs cause some form of pause, and they can meet different needs. The wait() method is used for interthread communication and releases the lock if the wait condition is true and another thread is awakened, while the sleep() method only releases CPU resources or stops the current thread from executing for a period of time, but does not release the lock. Note that sleep() does not terminate the thread. Once it is woken from sleep, the thread’s state will be changed to Runnable and it will be executed according to thread scheduling.

53, What is Thread Group? Why is it not recommended?

ThreadGroup is a class whose purpose is to provide information about thread groups.

The ThreadGroup API is weak and does not provide more functionality than Thread. It has two main functions: one is to get the list of active threads in the thread group; The second is to set the nCaught Exception handler for the thread. But the Thread in the Java 1.5 class also added setUncaughtExceptionHandler (UncaughtExceptionHandler eh) method, so the ThreadGroup is outdated, continue to use is not recommended.

What is a Java Thread Dump and how do I get it?

A thread dump is a list of active JVM threads that are useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump — using Profiler, the Kill -3 command, the JStack tool, and so on. We prefer the JStack tool because it is easy to use and comes with the JDK. Since it is a terminal-based tool, we can write scripts to periodically generate thread dumps for analysis.

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

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

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.

In Java. Util. Concurrent. Atomic package after adding the atomic variable classes, this kind of situation is changed. All atomic variable classes expose compare and set primitives (similar to compare and swap) that are implemented using the fastest native constructs available on the platform (compare and swap, load links/conditional stores, and, in the worst case, spin locks). Java. Util. Concurrent. Atomic package provides the 9 kinds of style of atomic variables (AtomicInteger; AtomicLong; AtomicReference; AtomicBoolean; Atomic integer type; Long; Reference; And an array form of the atom tag reference and stamp reference classes that update a pair of values atomically.

57, 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

58. What is the Executor Framework?

Executor framework with Java. Util. Concurrent. The Executor interface was introduced in Java 5. 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. The Executor framework makes it very easy to create a thread pool.

Executors what is?

Executors provide tools and methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

Executors can be used to easily create thread pools.

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

Java. Util. Concurrent. BlockingQueue feature is: when the queue is empty, the operation of the access to or remove elements from the queue will be blocked, or when the queue is full, add elements in the queue will be blocked.

Blocking queues do not accept null values and will throw a NullPointerException when you try to add a null value to the queue.

Blocking queue implementations are thread-safe, all query methods are atomic and use internal locks or other forms of concurrency control.

The BlockingQueue interface is part of the Java Collections framework and is primarily used to implement producer-consumer problems.

61. What are Callable and Future?

Java 5 in concurrency package introduced in Java. Util. Concurrent. Callable interface, it is similar to the Runnable interface, but it can return an object or throw an exception.

The Callable interface uses generics to define its return type. The Executors class provides some useful methods for executing Callable tasks in the thread pool. Since the Callable task is parallel, we must wait for the result it returns. Java. Util. Concurrent. The Future object to solve the problem for us. A Future object is returned after the Callable task is submitted by the thread pool. It can be used to know the status of the Callable task and get the execution result returned by the Callable. The Future provides a get() method that lets us wait for the Callable to end and get its execution result.

62 What is FutureTask?

The FutureTask wrapper is a very convenient mechanism for converting Callable into Future and Runnable, and it implements interfaces for both.

The FutureTask class is an implementation of the Future and implements Runnable, so it can be executed through an Excutor(thread pool). It can also be passed to Thread objects for execution. If you need to perform time-consuming operations on the main thread but don’t want to block the main thread, you can hand them over to the Future to be done in the background. When the main thread needs them in the Future, the Future object can be used to obtain the results of the calculation or execution status of the background job.

63. What is the implementation of concurrent containers?

Java collection classes are rapid failure, this means that when the set is changed and a thread when using iterators iterate through the set, iterator next () method will throw ConcurrentModificationException.

Concurrent containers: concurrent containers are designed for concurrent access by multiple threads. The concurrent package introduced in jdk5.0 provides concurrent containers such as ConcurrentHashMap, CopyOnWriteArrayList, etc.

Concurrent containers use a completely different locking strategy from synchronous containers to provide higher concurrency and scalability. For example, in ConcurrentHashMap, a more granular locking mechanism is used, which can be called segment-based locking. In this locking mechanism, any number of reader threads 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.

What is the difference between a user thread and a daemon thread?

When we create a thread in a Java program, it is called a user thread. A daemon thread is one that executes in the background and does not prevent the JVM from terminating. When no user threads are running, the JVM closes the program and exits. A child thread created by a daemon thread is still a daemon thread.

What are the different thread lifecycles?

When we create a New thread in a Java program, its state is New. When we call the thread’s start() method, the state is changed to Runnable. The thread scheduler allocates CPU time to the threads in the Runnable thread pool and changes their state to Running. Other thread states include Waiting, Blocked, and Dead.

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.

Why are Thread’s sleep() and yield() methods 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.

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.

Thread scheduling policy?

(1) Preemptive scheduling strategy

The Java runtime system’s thread scheduling algorithm is preemptive. The Java runtime system supports a simple fixed-priority scheduling algorithm. If a thread with a higher priority than any other runnable thread enters the ready state, the run-time system selects that thread to run. The new higher priority thread preempt the other threads. But the Java runtime system does not preempt threads of the same priority. In other words, the Java runtime system is not time-slice. However, an implementation system based on the Java Thread class is likely to support time-sharing, so don’t rely on time-sharing when writing code. When all the ready threads in the system have the same priority, the thread scheduler uses a simple, non-preemptive rotation of the scheduling order.

(2) Time slice rotation scheduling strategy

Some systems employ round-robin scheduling. This scheduling strategy allocates CPU time to the thread with the highest priority among all threads in the ready state. Select another thread to run after this time. Only when the thread finishes running, yields the CPU, or for some reason enters a blocking state do low-priority threads have a chance to execute. If there are two threads of the same priority that are both waiting for the CPU, the scheduler selects the running thread on a rotating basis.

How do you handle uncatched exceptions in threads?

Thread. UncaughtExceptionHandler is the new interface in Java SE5, it allows us to add in each Thread objects an exception handler.

conclusion

Also do not know what to say, in short, praise, look, collect, three even walk!