Advanced Java Multithreading Interview Questions And Answers

Interview Questions

43 Java Multithreading Interview Questions And Answers – Multithreading in Java Interview Questions For Experienced 2018 from Codingcompiler. Test your Java multithreading knowledge by answering these tricky interview questions on Java Multithreading. Let’s start learning Java Multithreading interview questions and prepare for Java interviews. All the best for your future and happy learning.

Java Multithreading Interview Questions

  1. Define the concept of “process”.
  2. Give the definition of “flow”.
  3. Define the concept of “thread synchronization”.
  4. How do programs, processes and threads interact?
  5. When is it appropriate to create multiple streams?
  6. What can happen if two threads execute the same code in the program?
  7. What do you know about the main program flow?
  8. What are the ways to create and run streams?
  9. Which method starts a thread for execution?
  10. What method describes the flow action at run time?
  11. When does the thread finish its execution?
  12. How to synchronize a method?
  13. How to forcibly stop the flow?
  14. Give the definition of the concept of “flow-demon”.
  15. How to create a daemon thread?
  16. How to get current stream?
  17. Give the definition of “monitor”.
  18. How to suspend the flow?
  19. In what conditions can the flow be?
  20. What is a monitor when calling a non-static and static method?
  21. What is a monitor when executing a portion of a method code?
  22. What methods allow you to synchronize the execution of threads?
  23. What method puts a stream on standby?
  24. What is the functionality of the notify and notifyAll methods?
  25. What does the join method do?
  26. What are the conditions for calling the wait / notify method?
  27. Define the concept of “interlocking”.
  28. What is the difference between interrupt, interrupted and isInterrupted methods?
  29. In which case the InterruptedException will be thrown, what methods can throw it?
  30. Modifiers volatile and the yield () method.
  31. Package java.util.concurrent
  32. There is some method that performs the operation i ++. The variable i is of type int. It is assumed that the code will be executed in a multithreaded environment. Should I sync the block?
  33. What is used as a mutex if the method is declared static synchronized? Can I create new class instances while the static synchronized method is running?
  34. Suppose in the run method a RuntimeException occurred that was not caught. What happens to the flow? Is there a way to know that an Exception has occurred (without enclosing the entire run body in a try-catch block)? Is there a way to restore the thread after it happened?
  35. What standard Java tools would you use to implement a thread pool?
  36. What is a ThreadGroup and why is it needed?
  37. What is a Thread Pool and why is it needed?
  38. What is a ThreadPoolExecutor and why is it needed?
  39. What is “atomic types” in Java?
  40. Why do I need a class ThreadLocal?
  41. What is Executor?
  42. What is ExecutorService?
  43. Why do I need ScheduledExecutorService?

Related Java Interview Questions

  1. Java IO Interview Questions
  2. Java String Interview Questions
  3. Java Collections Interview Questions
  4. Java Exceptions Interview Questions
  5. Java OOPS Interview Questions
  6. Core Java Interview Questions
  7. JSF Interview Questions
  8. JSP Interview Questions
  9. JPA Interview Questions
  10. Spring Framework Interview Questions
  11. Spring Boot Interview Questions
  12. Core Java Multiple Choice Questions
  13. 60 Java MCQ Questions And Answers
  14. Aricent Java Interview Questions
  15. Accenture Java Interview Questions
  16. Advanced Java Interview Questions For 5 8 10 Years Experienced
  17. Core Java Interview Questions For Experienced

Java Multithreading Interview Questions

1. Define the concept of “process”.

A process is a collection of code and data that shares a common virtual address space. Processes are isolated from each other, therefore direct access to the memory of another process is impossible (interaction between processes is carried out using special means).

For each process, the OS creates a so-called “virtual address space” to which the process has direct access. This space belongs to the process, contains only its data and is at its complete disposal. The operating system is responsible for how the virtual space of the process is projected onto the physical memory.

2. Give the definition of “flow”.

One thread (“thread” or “trade”) is one unit of code execution. Each thread sequentially executes instructions of the process to which it belongs, in parallel with other threads of this process.

3. Define the concept of “thread synchronization”.

Synchronization refers to multithreading. A synchronized block of code can only be executed by one thread at a time.

Java supports multiple threads for execution. This can result in two or more threads accessing the same field or object. Synchronization is a process that allows you to run all parallel threads in a program synchronously. Synchronization avoids memory consistency errors caused by inconsistent access to shared memory.

When a method is declared as synchronized, the thread holds the monitor for the object whose method is executed. If another thread performs a synchronized method, your thread will block until another thread releases the monitor.

Synchronization is achieved in Java using the synchronized reserved word. You can use it in your classes by defining synchronized methods or blocks. You cannot use synchronized in variables or attributes in the class definition.

4. How do programs, processes and threads interact?

Most often, one program consists of one process, but there are exceptions (for example, the Chrome browser creates a separate process for each tab, which gives it some advantages, such as the independence of tabs from each other).

Multiple threads can be created in each process. Processes are divided among themselves (> programs), threads in one process can interact with each other (methods of wait, notify, join, etc.).

5. When is it appropriate to create multiple streams?

Multi-threaded applications are used in cases where the program can be divided into several relatively independent parts. In this case, so that one code does not wait for the other, they are placed in different threads.

As an example, a program with a graphical interface can be given – as long as any lengthy computations are performed in one thread, the interface can be accessible to the user and not hang if it is running in another thread.

6. What can happen if two threads execute the same code in the program?

If non-synchronized data is used, a situation may occur when the code is already working with obsolete data. For example, in the first stream there is a change in any fields, and at this time the second stream reads these fields.

7. What do you know about the main program flow?

Small Java programs usually consist of a single thread, called the main thread. But more programs often run additional threads, they are also called “child threads”.

The main thread executes the main method and ends. The analogue of such a main method, for child threads, is the Runnable interfaces run method. Many threads – many methods main (run ()).

8. What are the ways to create and run streams?

There are several ways to create and launch streams.

Using a class that implements Runnable

  • Create an object of class Thread .
  • Create a class object that implements the Runnable interface.
  • Call the start () method on the created Thread object (after that, the run () method of the passed object that implements Runnable will start )

Using a class that extends Thread

  • Create an object of class ClassName extends  Thread .
  • Override run () in this class (see the example below, where the stream name is ‘Second’)

Using a class that implements java.util.concurrent.Callable

  • Create a class object that implements the Callable interface
  • Create an ExecutorService object with an indication of the thread pool.
  • Create a future object. The launch takes place through the submit () method ; Signature:  <T> Future <T> submit (Callable <T> task)
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

   public static void howToRunThreads() {

       ThreadClass threadClass = new ThreadClass(“First”);

       threadClass.start(); //method ThreadClass.run()

       Thread thread = new Thread(new RunnableClass(“Second”));

       Thread thread2 = new Thread(new RunnableClass(“Third”));

       Thread thread3 = new Thread(new RunnableClass(“Fourth”));

       thread.start(); //method RunnableClass.run()

       thread2.start(); //method RunnableClass.run()

       thread3.start(); //method RunnableClass.run()

   }

public class RunnableClass implements Runnable {

   private String localName;

   public RunnableClass() {

   }

   public RunnableClass(String localName) {

       this.localName = localName;

   }

   @Override

   public void run() {

       System.out.println(“run() ” + localName + ” running”);

   }

   public String getLocalName() {return localName;}

   public void setLocalName(String localName) {this.localName = localName;}

}

public class ThreadClass extends Thread {

   public ThreadClass() {

   }

   public ThreadClass(String name) {

       super(name);

   }

   public ThreadClass(Runnable target) {

       super(target);

       System.out.println(target + ” will running”);

   }

   @Override

   public void run() {

     System.out.println(“ThreadClass run() method ” + “Thread name is: ” + this.getName());

   }

}

// Conclusion

ThreadClass run() method Thread name is: First

run() Third running

run() Fourth running

run() Second running //note swapped at runtime.

Callable interface example :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

public class CallableExample {

 public static class WordLengthCallable

       implements Callable {

   private String word;

   public WordLengthCallable(String word) {

     this.word = word;

   }

   public Integer call() {

     return Integer.valueOf(word.length());

   }

 }

 public static void main(String args[]) throws Exception {

   ExecutorService pool = Executors.newFixedThreadPool(3);

   Set<Future<Integer>> set = new HashSet<Future<Integer>>();

   for (String word: args) {

     Callable<Integer> callable = new WordLengthCallable(word);

     Future<Integer> future = pool.submit(callable);

     set.add(future);

   }

   int sum = 0;

   for (Future<Integer> future : set) {

     sum += future.get();

   }

   System.out.printf(“The sum of lengths is %s%n”, sum);

   System.exit(sum);

 }

}

9. Which method starts a thread for execution?

Thread.start () starts a child thread. For the Callable interface, the thread is launched using the submit () method.

10. What method describes the flow action at run time?

The run () method or call () method for child threads. The main () method for the main thread.

Multithreading in Java Interview Questions

11. When does the thread finish its execution?

The thread finishes execution when its run () or call () method completes. For the main thread, this is the main () method.

12. How to synchronize a method?

Either specify the synchronized modifier in the signature or use the synchronized {} construct inside the method.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

   public void swap()

   {

       synchronized (this)

       {

       //someCode

       }

   }

   public synchronized void swap1EqualsSwap()

   {

   //someCode

   }

   public static synchronized void swap2()

   {

   //someCode

   }

   public static void swap3EqualsSwap2()

   {

       synchronized (JoinClass.class)

       {

           //someCode

       }

   }

13. How to forcibly stop the flow?

In Java 8, there is no method that would force the stream to stop. No one guarantees that the thread can be stopped. She can only stop herself. Java has a built-in stream alert mechanism called Interruption.

The Thread class contains a hidden boolean field called the interrupt flag. You can set this flag by calling the threads interrupt () method. There are two ways to check if this flag is set. The first way is to call the bool isInterrupted () method of the thread object, the second is to call the static method bool Thread.interrupted ().

The first method returns the state of the interrupt flag and leaves this flag intact. The second method returns the state of the flag and resets it. Notice that Thread.interrupted () is a static method of the Thread class, and calling it returns the value of the interrupt flag of the thread from which it was called. Therefore, this method is called only from within the thread and allows the thread to check its interrupt state.

Methods that suspend the execution of a thread, such as sleep (), wait () and join (), have one feature – if the interrupt () method of this thread is called during their execution, they will wait for the end of the wait time to throw an InterruptedException exception.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

public class JoinClass implements Runnable {

   @Override

   public void run() {

       for (int i=0; i<100; i++) {

           if(!Thread.interrupted()) {

               System.out.println(i);

               try {

                   Thread.sleep(100);

               } catch (InterruptedException e) {

                   System.out.println(“InterruptedException!”);

                   System.err.println(“Exception msg: ” + e.getMessage());

                   return;

               }

           } else {

               System.out.println(“Interrupted!”);

               return;

           }

       }

   }

}

public class TestClass {

   public static void main(String[] args) {

       Thread thread = new Thread(new JoinClass());

       thread.start();

       try {

           Thread.sleep(1000L); // turn off the main stream to JoinClass.run() something managed to be counted

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

       thread.interrupt();

   }

}

// Conclusion

0

1

8

9 // counter was up to 100

InterruptedException!

Exception msg: sleep interrupted

  • In the main () method, we create an object of the JoinClass class and run it with the run () method  . First, it is checked whether this stream is already completed, and then the counter value is output every 100 ms.
  • He orders the main method to wait 1000ms so that the meter has time to count a little.
  • Call the interrupt method on an object of the class JoinClass . After that, an exception is immediately caught in the loop and the return is raised in the catch block .

14. Give the definition of the concept of “flow-demon”.

Demon threads are threads that run in the background for our program.

In Java, a process terminates when its last thread terminates. Even if the main () method has already completed, but the threads generated by it are still running, the system will wait for them to complete.

However, this rule does not apply to a special type of thread – demons. If the last normal process thread has ended, and only the daemons are left, they will be forcibly terminated and the process will end. Most often, daemon threads are used to perform background tasks that serve the process throughout its life.

15. How to create a daemon thread?

It is quite simple to declare a thread as a daemon – you need to call its setDaemon (true) method before starting the stream ;

You can check whether a thread is a daemon by calling its boolean isDaemon () method ;

1

2

3

Thread thread = new Thread(new DaemonClass());

thread.setDaemon(true);

System.out.println(thread.isDaemon()); //true

16. How to get current stream?

Call the static method Thread.currentThread () in the code  , which returns the current thread.

17. Give the definition of “monitor”.

Multiple threads can interfere with each other when accessing the same data. To solve this problem, a mutex was created (a monitor). It has two states – the object is busy and the object is free. Monitor (mutex) is a high-level mechanism for interaction and synchronization of threads, providing access to unshared resources.

When a thread needs an object common to all threads, it checks the mutex associated with this object. If the mutex is free, the thread locks it (marks as busy) and starts using the shared resource. After she has done her work, the mutex is unlocked (marked as free).

If the thread wants to use the object, and the mutex is blocked, then the thread falls asleep while waiting. When the mutex is finally released by a busy thread, our thread will immediately block it and start work. The mutex is built into the Object class and therefore every object has it.

When one thread goes inside a block of code marked with the word synchronized, the Java machine immediately blocks the mutex of the object, which is indicated in parentheses after the word synchronized.

No other thread can enter this block until our thread leaves it. As soon as our thread comes out of the block marked synchronized, the mutex will immediately unlock automatically and be free to be captured by another thread. If the mutex was busy, then our thread will stand still and wait for it to be released.

18. How to suspend the flow?

Thread.sleep () is a static method of class Thread, which suspends the execution of the thread in which it was called. During the execution of the sleep () method, the system stops allocating CPU time to the thread, distributing it among other threads.

The sleep () method can run either for a specified amount of time (milliseconds or nanoseconds) or until it is stopped by an interrupt (in this case, it throws an InterruptedException exception).

There is a question about the old methods of suspend, stop and resume – they are deprecated.

19. In what conditions can the flow be?

A stream can be in the following state: created, started, blocked, stopped, in standby mode, in standby mode by time (NEW, RUNNABLE, BLOCKED, TERMINATED, WAITING, TIMED_WAITING).

20. What is a monitor when calling a non-static and static method?

For a non-static method, the current object is this. For a static method, an object of type Class that corresponds to the class in which this method is defined.

Java Multithreading Concurrency Interview Questions and Answers

21. What is a monitor when executing a portion of a method code?

A monitor is an object specified in a synchronized block of code:

1

2

3

4

5

       synchronized (synchedList) {

               synchedList.wait();

       }

22. What methods allow you to synchronize the execution of threads?

These methods include notify (), notifyAll (), wait ();

23. What method puts a stream on standby?

The wait () method.

24. What is the functionality of the notify and notifyAll methods?

The notify method awakens one of the threads that called the wait () method on this monitor. The notifyAll method wakes up all threads. The order of execution in this case will be determined by the priority of the thread.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

public class NotifyClass {

   private List synchedList;

   public NotifyClass() {

       // create a new synchronized list to be used

       synchedList = Collections.synchronizedList(new LinkedList());

   }

   // method used to remove an element from the list

   public String removeElement() throws InterruptedException {

       synchronized (synchedList) {

           // while the list is empty, wait

           while (synchedList.isEmpty()) {

               System.out.println(“List is empty…”);

               synchedList.wait();

               System.out.println(“Waiting…”);

           }

           String element = (String) synchedList.remove(0);

           return element;

       }

   }

   // method to add an element in the list

   public void addElement(String element) {

       System.out.println(“Opening…”);

       synchronized (synchedList) {

           // add an element and notify all that an element exists

           synchedList.add(element);

           System.out.println(“New Element:'” + element + “‘”);

           synchedList.notifyAll();

           System.out.println(“notifyAll called!”);

       }

       System.out.println(“Closing…”);

   }

   public static void main(String[] args) {

       final NotifyClass demo = new NotifyClass();

       Runnable runA = new Runnable() {

           public void run() {

               try {

                   String item = demo.removeElement();

                   System.out.println(“” + item);

               } catch (InterruptedException ix) {

                   System.out.println(“Interrupted Exception!”);

               } catch (Exception x) {

                   System.out.println(“Exception thrown.”);

               }

           }

       };

       Runnable runB = new Runnable() {

           // run adds an element in the list and starts the loop

           public void run() {

               demo.addElement(“Hello!”);

           }

       };

       try {

           Thread threadA1 = new Thread(runA, “A”);

           threadA1.start();

           Thread.sleep(500);

           Thread threadA2 = new Thread(runA, “B”);

           threadA2.start();

           Thread.sleep(500);

           Thread threadB = new Thread(runB, “C”);

           threadB.start();

           Thread.sleep(1000);

           threadA1.interrupt();

           threadA2.interrupt();

       } catch (InterruptedException x) {

       }

   }

}

// Conclusion

List is empty…

List is empty…

Opening…

New Element:’Hello!’

notifyAll called!

Closing…

Waiting…

Waiting…

List is empty…

Hello!

Interrupted Exception!

25. What does the join method do?

One thread (thread) can call the join () method on another thread. As a result, the first thread (which called the method) suspends its work and waits for the second thread to finish (the object whose call () method was called).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public class TestClass {

   public static void main(String[] args) {

       Thread threadExample = new Thread(new JoinClass());

       threadExample.start();

       try {

           threadExample.join(); //public static void TestClass.main() connect to threadExample and wait for it.

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

       System.out.println(“END: ” + Calendar.getInstance().getTime());

   }

}

public class JoinClass implements Runnable {

   @Override

   public void run() {

             System.out.println(“JoinClass.run() ” + Calendar.getInstance().getTime());

       try {

           Thread.sleep(5000L);

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

       System.out.println(“afterSleep ” + Calendar.getInstance().getTime());

   }

}

// Conclusion

JoinClass.run() Tue Jan 19 00:00:37 MSK 2016

afterSleep Tue Jan 19 00:00:42 MSK 2016

END: Tue Jan 19 00:00:42 MSK 2016

After launching the main method , the main thread of the TestClass class is created .

  • Then we create a thread test threadExample and run it. We set the thread to stupit 5 seconds inside the JoinClass.run () method .
  • Then we call the join () method on the second thread. At this point, the main thread connects to our second thread and waits for it to complete.
  • We look at what time has passed – 5 seconds. Those. the main thread waited for threadExample to complete before going to the System.out.println () method . Otherwise, System.out.println (“END:“) was  executed immediately without waiting for threadExample to go.

26. What are the conditions for calling the wait / notify method?

Methods should be called on the monitor object only from synchronized code. The thread that calls these methods must own the monitor, otherwise a java.lang.IllegalMonitorStateException exception will be thrown  .

27. Define the concept of “interlocking”.

Deadlock, it is also a deadlock, a phenomenon in which all threads are in standby mode. To reduce the chance of a deadlock, it is not recommended to use the wait () and notify () methods.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

   final Object lock1 = new Object();

   final Object lock2 = new Object();

   

// There will be deadlock

   void method01() {

       synchronized(lock1) {

           synchronized(lock2) {

           //doSomething()

           }

       }

   }

   

   void method1() {

       synchronized(lock2) {

           synchronized(lock1) {

           //doSomething()

           }

       }

   }

To avoid deadlock, you can use only one synchronized block, refuse from wait-notify, or use the following construction:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//To avoid deadlock

//If you can’t use only one lock, then use this scheme

   void method2() {

       if (identityHashCode(lock1)>=identityHashCode(lock2)) {

           synchronized(lock1) {

               synchronized(lock2) {

                 //doSomething()

               }

           }

       }

       else {

           synchronized(lock2) {

               synchronized(lock1) {

               //doSomething()

               }

           }

       }

   }

28. What is the difference between interrupt, interrupted and isInterrupted methods?

  • The interrupt () method sets the thread interrupt flag.
  • The bool isInterrupted () method of the thread object returns the state of the interrupt flag and leaves this flag intact.
  • Static method bool Thread.interrupted () – returns the state of the flag and resets it.

29. In which case the InterruptedException will be thrown, what methods can throw it?

Methods requiring this exception to be processed: wait, sleep, join. An exception will be thrown if the interrupt flag of the thread is true.

Java Thread Interview Questions Answers for Experienced

30. Modifiers volatile and the yield () method.

Placing the volatile modifier before defining a variable forces it to always read and write the value only to normal (slow) memory (and not to cache). It is written as: private volatile boolean varName;

The static method Thread.yield () forces the processor to switch to processing other system threads. The method can be useful, for example, when the flow is waiting for the occurrence of an event and it is necessary that the test of its occurrence occurs as often as possible. In this case, you can put the event check and the Thread.yield () method into a loop:

1

2

3

4

5

//Message waiting

while(!msgQueue.hasMessages()) //No messages in the queue yet

{

Thread.yield(); //Transfer control to other threads

}

31. Package java.util.concurrent

Java.util.concurrent. 

32. There is some method that performs the operation i ++. The variable i is of type int. It is assumed that the code will be executed in a multithreaded environment. Should I sync the block?

Yes, otherwise there will be a race condition.

33. What is used as a mutex if the method is declared static synchronized? Is it possible to create new class instances while the static synchronized method is running?

Yes, you can create a new instance of a class while its static synchronized method is executed. My reasoning: the static class methods are created in a single instance during class loading by the class-clander and belong to the Class.MyClass object.

At runtime, the lock of this particular object is captured in the static synchronized method. Consequently, nothing prevents us from creating a new instance of the class.

There may be several loaders, respectively, instances of Class <MyClass> – also several, one per loader. To create a new instance does not interfere, because this is a type of machine allocation for an object and a method call that is not synchronized.

34. Suppose in the run method a RuntimeException occurred that was not caught.

What happens to the flow?

Is there a way to know that an Exception has occurred (without enclosing the entire run body in a try-catch block)?

Is there a way to restore the thread after it happened?

If Exception fails in the child thread, the run () method will crash and the exception will be passed to the main thread. Next, the console will be displayed in the console below.

If the exception is not processed, then the thread (called in the run () method) will simply crash. To restore the work of the thread after such a scenario is impossible, you can only create a thread again.

1

2

3

4

5

Exception in thread “Thread-0” java.lang.NullPointerException

Thread-0

at ru.javastudy.interview.multithreading.JoinClass.exceptionChecker(JoinClass.java:101)

at ru.javastudy.interview.multithreading.JoinClass.run(JoinClass.java:24)

at java.lang.Thread.run(Thread.java:745)

35. What standard Java tools would you use to implement a thread pool?

Read about the concurrent package. The implementation of standard packages in an article.

36. What is a ThreadGroup and why is it needed?

ThreadGroup is a set of threads that can also contain other groups of threads. A group of threads forms a tree in which every other group of threads has a parent (except the original one). A thread has the right to access data from its thread group, but does not have such access to other groups or to the parent group of threads.

37. What is a Thread Pool and why is it needed?

Thread pools (threads) are a managed collection of threads that are available for various tasks. Thread pools usually provide:

  • Increased productivity when performing a large number of tasks due to the reduction of overhead costs for the challenge of each task.
  • It is a means of limiting the expenditure of resources when performing a set of tasks.
  • Eliminate the need for thread life cycle management.

38. What is a ThreadPoolExecutor and why is it needed?

ThreadPoolExecutor is an implementation of ExecutorService. It performs the transferred task (Callable or Runnable) using one of the internal available threads from the pool. The thread pool contains a ThreadPoolExecutor, which can contain a varying number of threads. The number of threads in the pool is set using corePoolSize and maximumPoolSize.

Advanced Java Multithreading Interview Questions And Answers

39. What is “atomic types” in Java?

All atomic classes of variables have a base element Comparison and Purpose (compare-and-set) (similar to the Comparison and Replacement element), which is implemented using the fastest native structural component that is available in the platform (Comparison and Replacement, Download in a bundle, Save at condition or as a last resort spin-locks).

The java.util.concurrent.atomic package includes 9 types of atomic variables (AtomicInteger; AtomicLong; AtomicReference; AtomicBoolean; forms for arrays of atomic integers; long (long); links; and also atomic with the mark Class of reference, which are atomically update two values).

Classes of atomic variables can be viewed as a generalization of volatile variables by extending the notion of variable variables to variables with atomic updates support by the Comparison and Purpose method. Reading and writing atomic variables has the same memory semantics as access to reading and writing mutable variables.

AtomicLong atomic variable example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

private volatile long value;

public final long get() {

   return value;

}

public final long getAndAdd(long delta) {

   while (true) {

       long current = get();

       long next = current + delta;

       if (compareAndSet(current, next))

           return current;

   }

}

The variables current and next are local, and therefore each thread has its own instances of these variables. Attention should be paid only to the shared state, i.e. variable value. Since Since the value variable is declared with the volatile modifier, the execution of the happens-before relationship is guaranteed, which leads to the fact that all threads will see the changed value of this variable.

The compareAndSet method is an optimistic locking mechanism and allows you to change the value value only if it is equal to the expected value (ie, current).

If the value was changed in another thread, then it will not be equal to the expected value. Therefore, the compareAndSet method returns false, which will result in a new iteration of the while loop in the getAndAdd method. Those. The new value will be re-read into the current variable, after which addition and a new attempt to write the resulting value will be performed (ie, next).

40. Why do I need a class ThreadLocal?

ThreadLocal provides an abstraction over variables local to the execution thread java.lang.Thread. ThreadLocal variables differ from ordinary variables in that each thread has its own, individually initialized instance of a variable, which it can access via get () or set () methods.

Each thread – i.e. an instance of the class Thread – there is a table associated with it ThreadLocal-variables. The keys to the table are references to objects of the class ThreadLocal, and the values ​​are references to objects “captured” by ThreadLocal-variables.

41.What is Executor?

Executor is an interface that can perform confirmed tasks. The interface provides an opportunity to avoid understanding the mechanics of the task and the details of the use of the thread being executed. Executor is usually used to explicitly create threads. For example:

1

2

3

4

5

6

7

//Вместо

Thread(new(RunnableTask())).start():

//Лучше использовать

Executor executor = anExecutor;

executor.execute(new RunnableTask1());

executor.execute(new RunnableTask2());

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html

42.What is ExecutorService?

ExecutorService executes asynchronous code in one or more threads. Creating an ExecutorService instance is done either manually through specific implementations (ScheduledThreadPoolExecutor or ThreadPoolExecutor), but it will be easier to use the Executors class factory. For example, if you need to create a pool with 2 threads, this is done like this:

1ExecutorService service = Executors.newFixedThreadPool(2);

If you want to use a caching thread pool, which creates threads as needed, but reuses inactive threads (and cleans up threads that have been inactive for a while), then this is defined as follows:

1ExecutorService service = Executors.newCachedThreadPool();

If you want to run asynchronous code several times, it will be executed like this:

1

2

3

4

5

6

7

8

ExecutorService service = Executors.newCachedThreadPool();

for(int i = 0; i < 10; i++) {

service.submit(new Runnable() {

 public void run() {

  // snip… piece of code

 }

});

}

The submit method also returns a Future object that contains information about the execution status of the passed Runnable or Callable (which can return a value). From it you can find out whether the transferred code has been executed successfully, or is it still being executed.

Calling the get method on the Future object will return a value that returns Callable (or null if Runnable is used). The method has 2 checked-exceptions: InterruptedException, which is thrown when execution is interrupted via the interrupt () method, or ExecutionException if the code in Runnable or Callable threw a RuntimeException, which solves the problem of supporting exceptions between threads.

43. Why do I need ScheduledExecutorService?

Sometimes it is required to execute code periodically and periodically or it is required to execute code after some time, then ScheduledExecutorService comes to the rescue. It allows you to put the code to run in one or more threads and configure the interval or time for which the execution will be delayed. The interval can be the time between two consecutive starts or the time between the end of one execution and the beginning of another. The ScheduledExecutorService methods return a ScheduledFuture, which also contains the deferral value for running the ScheduledFuture.

If you want to delay execution for 5 seconds, you will need the following code:

1

2

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

service.schedule(new Runnable() { … }, 5, TimeUnit.SECONDS);

If you want to assign execution every second:

1

2

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

service.scheduleAtFixedRate(new Runnable() { … }, 0, 1, TimeUnit.SECONDS);

And finally, if you want to assign code execution with an interval of 1 second between executions:

1

2

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

service.scheduleWithFixedDelay(new Runnable() { … }, 0, 1, TimeUnit.SECONDS);

Must Read Java Interview Questions Books

RELATED INTERVIEW QUESTIONS

  1. Java IO Interview Questions
  2. Java String Interview Questions
  3. Java Collections Interview Questions
  4. Java Exceptions Interview Questions
  5. Java OOPS Interview Questions
  6. Core Java Interview Questions
  7. JSF Interview Questions
  8. JSP Interview Questions
  9. JPA Interview Questions
  10. Spring Framework Interview Questions
  11. Spring Boot Interview Questions
  12. Core Java Multiple Choice Questions
  13. 60 Java MCQ Questions And Answers
  14. Aricent Java Interview Questions
  15. Accenture Java Interview Questions
  16. Advanced Java Interview Questions For 5 8 10 Years Experienced
  17. Core Java Interview Questions For Experienced
  18. GIT Interview Questions And Answers
  19. Network Security Interview Questions
  20. CheckPoint Interview Questions
  21. Page Object Model Interview Questions
  22. Apache Pig Interview Questions
  23. Python Interview Questions And Answers
  24. Peoplesoft Integration Broker Interview Questions
  25. PeopleSoft Application Engine Interview Questions
  26. RSA enVision Interview Questions
  27. RSA SecurID Interview Questions
  28. Archer GRC Interview Questions
  29. RSA Archer Interview Questions
  30. Blockchain Interview Questions

1 thought on “Advanced Java Multithreading Interview Questions And Answers”

  1. Simply wish to say your article is as astounding.
    The clarity iin your publish is just great and tat i can suppose you’re a professional
    in this subject. Well along with your permission allow
    me to grasp your feed to stay updated with imminent post.
    Thank you a million and please continue the gratifying work.

Leave a Reply

Your email address will not be published. Required fields are marked *