Java multithreaded interview questions


Java multithreaded interview questions

1. What is a thread?

Thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. Programmers can use it for multiprocessor programming, and you can use multithreading to speed up computation intensive tasks. For example, if it takes 100 milliseconds for a thread to complete a task, it only takes 10 milliseconds for ten threads to complete the task. Java provides excellent support for multithreading at the language level, and it is also a good selling point. For more details, please click here.

2. What is the difference between threads and processes?

Threads are subsets of processes. A process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory space, and all threads share the same memory space. Don’t confuse it 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 at the language level. java. The instance of lang. thread class is a thread, but it needs to call Java Lang. runnable interface. Since the thread class itself is the runnable interface called, you can inherit Java Lang. thread class or directly call the runnable interface to override the run () method to implement the thread.

4. Runnable or thread?

This question is a follow-up to the previous question. As we all know, we can implement threads by inheriting the thread class or calling the runnable interface. The question is, which method is better? When to use it? 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 other classes, of course, call the runnable interface.

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

This question is often asked, but it can still distinguish the interviewer’s understanding of the Java threading model. The start () method is used to start the newly created thread, and start () internally calls the run () method, which is different from calling the run () method directly. When you call the run () method, it will only be called in the original thread. If no new thread is started, the start () method will start a new thread.

6. What is the difference between runnable and callable in Java?

Both runnable and callable represent tasks to be executed in different threads. Runnable from jdk1 Since 0, callable is in jdk1 5 increased. The main difference between them is that callable’s call () method can return values and throw exceptions, while runnable’s run () method does not have these functions. Callable can return the future object loaded with calculation 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 between different memory architectures, CPUs and operating systems. It is particularly important in the case of multithreading. The changes made by the Java Memory Model to one thread can be seen by other threads, which provides a guarantee that they are related in advance. This relationship defines some rules to make programmers think more clearly when programming concurrently. For example, a prior relationship ensures that:

The code in the thread can be executed in sequence, which is called program order rule.

For the same lock, one unlocking operation must occur before another locking operation after time, which is also called pipe locking rule.

The former write operation to volatile precedes the latter read operation, which is also called volatile variable rule.

Any operation within a thread must be after the start () call of the thread, which is also called thread start rule.

All operations of a thread will the thread termination rule before the thread terminates.

The termination operation of an object must be completed after the object is constructed, which is also called object termination rule.


9. What is the volatile variable in Java?

Volatile is a special modifier that can only be used by member variables. In the absence of synchronization classes in Java Concurrent Programs, the operation of multi threads on member variables is transparent to other threads. Volatile variable can ensure that the next read operation will occur after the previous write operation, which is the volatile variable rule of the previous question.

10. What is thread safety? Is vector a thread safe class?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as that of single thread, and the values of other variables are the same as expected, it is thread safe. When the same instance object of a thread safe counter class is used by multiple threads, there will be no calculation error. Obviously, you can divide collection classes into two groups, thread safe and non thread safe. Vector is thread safe using synchronization method, while ArrayList similar to it is not thread safe. Here I recommend a framework learning exchange circle. Communication and learning: in 1253431195 (there are a large number of interview questions and answers), some videos recorded by senior architects will be shared: spring, mybatis, netty source code analysis, the principle of high concurrency, high performance, distributed and micro service architecture, JVM performance optimization, distributed architecture, etc. These have become the necessary knowledge system for architects. You can also receive free learning resources, which has benefited a lot at present

11. What are race conditions in Java? Give an example.

Race conditions can lead to some bugs in the program in the case of concurrency. When multithreading competes for some resources, race conditions will be generated. If the program to be executed first fails to compete and is executed later, there will be some uncertain bugs in the whole program. Such bugs are difficult to find and will repeat because of random competition between threads.

12. How to stop a thread in Java?

Java provides a rich API, but it does not provide an API for stopping threads. JDK 1.0 originally had some control methods like stop(), suspend() and resume(), but they were abandoned in subsequent JDK versions due to potential deadlock threats. After that, the designer of Java API did not provide a compatible and thread safe method to stop a thread. When the run () or call () method is executed, the thread will end automatically. If you want to end a thread manually, you can use the volatile boolean variable to exit the loop of the run () method or cancel the task to interrupt the thread.

13. What is semaphore in Java?

Semaphore in Java is a new synchronization class, which is a counting signal. Conceptually, semaphores maintain a set of permissions. If necessary, each acquire () is blocked before the license is available, and then the license is obtained. Each release () adds a license, which may release a blocked acquirer. However, instead of using the actual license object, semaphore only counts the number of licenses available and takes action accordingly. Semaphores are often used in multithreaded code, such as database connection pools.

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

This is a tricky question. Many programmers will think that the task will block until there is a vacancy in the thread pool queue. In fact, if a task cannot be scheduled for execution, the ThreadPoolExecutor’s submit() method will throw a rejectedexecutionexception exception.

15. What is the difference between the submit () and execute () methods in the java thread pool?

Both methods can submit tasks to the thread pool. The return type of the execute () method is void, which is defined in the executor interface, while the submit () method can return the future object holding the calculation results. It is defined in the executorservice interface, which extends the executor interface. Other thread pool classes such as ThreadPoolExecutor and scheduledthreadpoolexecutor have these methods.

16. What is a blocking method?

Blocking method means that the program will wait for the method to complete without doing anything else. The accept () method of ServerSocket is to wait for the client to connect. Blocking here means that the current thread will be suspended before the call result is returned and will not return until the result is obtained. In addition, there are asynchronous and non blocking methods that return before the task is completed.

17. Is swing thread safe? Why?

You can definitely answer that swing is not thread safe, but you should explain the reason for this answer, even if the interviewer doesn’t ask you why. When we say that swing is not thread safe, we often mention its components. These components cannot be modified in multiple threads. All updates to GUI components should be completed in AWT threads, while Swing provides synchronous and asynchronous callback methods to update. Here I recommend a framework learning exchange circle. Communication and learning: in 1253431195 (there are a large number of interview questions and answers), some videos recorded by senior architects will be shared: spring, mybatis, netty source code analysis, the principle of high concurrency, high performance, distributed and micro service architecture, JVM performance optimization, distributed architecture, etc. These have become the necessary knowledge system for architects. You can also receive free learning resources, which has benefited a lot at present

18. What is the difference between invokeandwait and invokelater in Java?

These two methods are provided by swing API to Java developers to update GUI components from the current thread rather than the event dispatch thread. Invokeandwait() synchronously updates GUI components, such as a progress bar. Once the progress is updated, the progress bar should also be changed accordingly. If the progress is tracked by multiple threads, the invokeandwait () method is called to request the event dispatch thread to update the component accordingly. The invokelater () method updates the component asynchronously.

19. Which methods in swing API are thread safe?

This problem also refers to swing and thread safety. Although components are not thread safe, there are some methods that can be called safely by multiple threads, such as repeat(), revalidate(). The settext () method of JTextComponent and the insert () and append () methods of jtextarea are also thread safe.

20. How to create immutable objects in Java?

This problem seems to have nothing to do with multithreading, but invariance helps simplify already complex concurrent programs. Immutable objects can be shared without synchronization, which reduces the synchronization overhead when accessing the object concurrently. However, Java does not have the @ immutable annotation. To create an immutable class, you need to implement the following steps: initialize all members through the construction method, do not provide setter methods for variables, and declare all members private. In this way, direct access to these members is not allowed. In the getter method, do not directly return the object itself, but clone the object and return a copy of the object.