JavaRush /Java Blog /Random EN /Translation: Top 50 interview questions by thread. Part 2...
KapChook
Level 19
Volga

Translation: Top 50 interview questions by thread. Part 2.

Published in the Random EN group
The second part of the translation of the original article Top 50 Java Thread Interview Questions Answers for Freshers, Experienced Programmers. First part.
  1. How to check if a thread is holding a lock?

  2. I had no idea that you could check whether a thread was currently holding a lock until I came across this question in a phone interview. java.lang.Thread has a holdsLock() method, it returns true if and only if the current thread is holding the monitor on a specific object.
  3. How to get a thread dump?

  4. A thread dump allows you to find out what a thread is currently doing. There are several ways to obtain a thread dump, depending on the operating system. On Windows you can use the combination ctrl + Break, on Linux you can use the kill -3 command. You can also use the jstack utility; it operates on the process id, which you can find out using another jps utility.
  5. What JVM parameter is used to control the thread's stack size?

  6. This is one of the simple, -Xss parameter used to control the size of a thread's stack in Java.
  7. Differences between synchronized and ReentrantLock?

  8. There were times when the only way to achieve mutual exclusion was through the synchronized keyword, but it has several disadvantages, such as not being able to extend lock beyond a method or code block, etc. Java 5 solves this problem by providing more granular control through the Lock interface. ReentrantLock is a common Lock implementation that provides a Lock with the same basic behavior and semantics as an implicit monitor, achieved using synchronized methods, but with enhanced capabilities.
  9. Given 3 threads T1, T2 and T3? How to implement the sequence T1, T2, T3?

  10. Consistency can be achieved in many ways, but you can simply use the join() method to start a thread when another has finished executing. To implement the given sequence, you need to start the last thread first, and then call the join() method in reverse order, that is, T3 calls T2.join and T2 calls T1.join, so T1 will finish first and T3 last.
  11. What does the yield method do?

  12. The yield method is one way to ask a thread to give up CPU so that another thread can execute. This is a static method and it only ensures that the current thread will give up the processor, but does not decide which thread execution will go to.
  13. What is the concurrency level of ConcurrentHashMap?

  14. ConcurrentHashMap achieves its scalability and thread safety by splitting the actual map into sections. This separation is achieved by using a level of parallelism. This is an optional parameter to the ConcurrentHashMap constructor and its default value is 16.
  15. What is Semaphore?

  16. Semaphore is a new type of synchronizer. This is a semaphore with a counter. Conceptually, a semaphore controls a set of permissions. Each acquire() blocks, if necessary, before the permission is available, then acquires it. Each release() adds a permission, potentially releasing the blocking acquirer. However, this does not use actual permission objects; Semaphore simply stores the number of available ones and acts accordingly. Semaphore is used to protect expensive resources that are available in limited quantities, such as a connection to a pooled database.
  17. What happens if the thread pool queue is already full and you submit a task?

  18. If the thread pool queue is full, the submitted task will be "rejected". ThreadPoolExecutor's submit() method throws a RejectedExecutionException, after which the RejectedExecutionHandler is called.
  19. Differences between submit() and execute() methods on a thread pool?

  20. Both methods are ways of submitting a task to a thread pool, but there is a slight difference between them. Execute(Runnable command) is defined in the Executor interface and executes the given task in the future, but more importantly, does not return anything. On the other hand, submit() is an overloaded method, it can accept Runnable and Callable tasks and can return a Future object that can be used to cancel execution and/or wait for the result of a calculation. This method is defined in the ExecutorService interface, which inherits from the Executor interface, and each thread pool class, such as ThreadPoolExecutor or ScheduledThreadPoolExecutor, inherits these methods.
  21. What is a blocking method?

  22. A blocking method is a method that blocks until the task is completed, for example, the ServerSocket accept() method blocks while waiting for the client to connect. Here, blocking means that control will not return to the calling method until the job is completed. On the other hand, there are asynchronous or non-blocking methods that complete before the task is completed.
  23. Is Swing thread safe?

  24. Simply put, no, Swing is not thread-safe, but you need to explain what you mean by that, even if the interviewer doesn't ask. When we say that Swing is not thread-safe, we usually refer to the fact that it is a component that cannot be modified by multiple threads. All changes to GUI components must be made in the AWT thread, and Swing provides synchronous and asynchronous methods for scheduling such changes.
  25. Differences between invokeAndWait and invokeLater?

  26. These are two Swing API methods that allow developers to update GUI components from threads rather than from the Event Manager thread. InvokeAndWait() synchronously updates a GUI component such as a progress bar; each time progress is made, the bar must be updated to reflect the changes. If progress is being tracked in another thread, it must call invokeAndWait() to assign the Event Dispatcher thread to update that component. And invokeLater() is an asynchronous call to update components.
  27. Which Swing API methods are thread-safe?

  28. This question is again about Swing and thread safety, although Swing components are not thread safe, there are methods that can be safely called from multiple threads. I know that repaint() and revalidate() are thread-safe, but there are other methods on different Swing components, such as JTextComponent's setText() and JTextArea's insert() and append() methods.
  29. How to create immutable objects?

  30. This question may seem to have nothing to do with multithreading and concurrency, but it does. Immutability helps simplify already complex parallel code. An immutable object is very expensive for developers because it can be propagated without any synchronization. Unfortunately, Java does not have the @Immutable annotation, which will make your object immutable, for this developers need to work hard. To create an immutable object, you need to follow the basics: initialization in the constructor, no setters, no reference leakage, storing separate copies of mutable objects.
  31. What is ReadWriteLock?

  32. In general, ReadWriteLock is the result of a lock parsing technique to improve the performance of parallel applications. This is an interface that was added in Java 5. It operates on a pair of related locks, one for read operations, one for write operations. A reader lock can be held simultaneously by several reading threads until there are no writers. The writing lock is exclusive. If you want, you can implement an interface with your ruleset, or you can use ReentrantReadWriteLock, which supports a maximum of 65535 recursive write locks and 65535 read locks.
  33. What is busy spin?

  34. Busy Spin is a technique programmers use to force a thread to wait under a certain condition. Unlike traditional methods, wait(), sleep() or yield(), which involve ceding control of the processor, this method does not cede the processor; instead, it simply executes an empty loop. Why would anyone do this? To save the processor cache. On multi-core systems, it is possible that a suspended thread will continue executing on another core, which means a cache rebuild. To avoid costly rebuilds, the programmer prefers to wait less by using busy spin.
  35. Differences between volatile and atomic variables?

  36. This is quite an interesting question, at first volatile and atomic variables look very similar, but they are still different. A Volatile variable provides a happens-before guarantee that a write will occur before any subsequent write; it does not guarantee atomicity. For example, the count++ operation will not become atomic simply because count is declared volatile. On the other hand, the AtomicInteger class provides an atomic method to perform such complex operations atomically, for example getAndIncrement() is an atomic replacement for the increment operator, it can be used to atomically increment the current value by one. There are also atomic versions for other data types.
  37. What happens if a thread throws an Exception in a synchronized block?

  38. This is another trick question for regular Java programmers. No matter how you exit a synchronized block, either normally by finishing execution or suddenly by throwing an exception, the thread releases the acquired lock when it enters the synchronized block. This is one of the reasons why I prefer a synchronized lock block to an interface that requires special care when releasing the lock, usually achieved by releasing the lock in a finally block.
  39. What is Singleton's double checked locking?

  40. This is one of the most popular interview questions, and yet, despite its popularity, the chances of a candidate answering it are 50% at best. Half the time they fail at writing the code, and the other half at explaining how it was broken and fixed in Java 1.5. This is an old way of creating a thread-safe singleton that tries to optimize performance by only blocking when the singleton instance is first instantiated, but due to the complexity and the fact that it was broken in JDK 1.4, I personally don't like it. Still, even if you don't prefer this approach, it's useful to know it from an interview perspective.
  41. How to create a thread-safe Singleton?

  42. This question complements the previous one. If you say you don't like double checked locking, then the interviewer will be forced to ask about alternative ways to create a thread-safe Singleton. And they are, you can take advantage of the class loading and static variable initialization features to instantiate Singleton, or you can take advantage of the powerful enum type.
  43. List 3 customs you follow in parallel programming?

  44. This is my favorite question because I believe there are certain rules that need to be followed when writing parallel code, which helps with performance, debugging, and support. Below are the 3 best rules that I believe every Java programmer should follow:
    • Always give meaningful names to your threads
    • Finding a bug or tracking down an exception in parallel code is a rather difficult task. OrderProcessor, QuoteProcessor or TradeProcessor is much better than Thread-1. Thread-2 and Thread-3. The name should reflect the task performed by the thread. All major frameworks and even JDK follow this rule.
    • Avoid blocking or reduce sync scope
    • Blocking is expensive, and context switching is even more expensive. Try to avoid synchronization and blocking as much as possible, and you will reduce the critical section to the minimum required. This is why I prefer a timed block over a timed method because it gives you absolute control over the extent of the blocking.
    • Between synchronizers and wait and notify, choose synchronizers
    • Firstly, synchronizers such as CountDownLatch, Semaphore, CyclicBarrier or Exchanger simplify coding. It is very difficult to implement complex control flow using wait and notify. Second, these classes are written and maintained by the best in the business and there is a good chance that they will be optimized or replaced with better code in future JDK releases. By using high-level synchronization utilities, you automatically gain all these benefits.
    • Between Concurrent Collection and Synchronized Collection, choose Concurrent Collection
    • This is another simple rule that is easy to follow and reap the benefits. Concurrent collections are more scalable than their synchronized counterparts, so it is better to use them when writing parallel code. So next time you need a map, think about ConcurrentHashMap before you think about Hashtable.
  45. How to force a thread to start?

  46. This is a question a la how to force garbage collection to run. In short, no way, you can of course make a query using System.gc(), but it doesn't guarantee anything. There is absolutely no way to force a thread to start in Java, this is controlled by the thread scheduler and Java does not provide any API to control it. This part of Java is still random.
  47. What is the Fork/Join framework?

  48. The Fork/Join framework introduced in JDK 7 is a powerful utility that allows the developer to take advantage of the multiple processors of modern servers. It is designed for work that can be recursively broken down into small particles. The goal is to use all available computing power to increase the performance of your application. One significant advantage of this framework is that it uses a work-stealing algorithm (from work - work and steal - to steal). Worker threads that have run out of jobs can steal jobs from other threads that are still busy.
  49. What is the difference between calls to wait() and sleep()?

  50. Although both wait and sleep represent a kind of pause in a Java application, they are devices for different needs. Wait is used for internal thread communication, it yields to lock if the wait condition is true, and waits for notification if another thread's actions make the wait condition false. On the other hand, the sleep() method simply gives up the processor or stops the current thread from executing for a specified amount of time. Calling sleep() does not release the lock held by the current thread.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION