Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java concurrency questions and answers

4,581 views

Published on

Questions on Java 8 Concurrency. It has answers and explanation too. This will be more useful OCPJP aspirants

Published in: Technology
  • Be the first to comment

Java concurrency questions and answers

  1. 1. Quiz Fun way to learn more Java Concurrency
  2. 2. Question You’ve written an application for processing tasks. In this application, you’ve separated the critical or urgent tasks from the ones that are not critical or urgent. You’ve assigned high priority to critical or urgent tasks. In this application, you find that the tasks that are not critical or urgent are the ones that keep waiting for an unusually long time. Since critical or urgent tasks are high priority, they run most of the time. Which one of the following multi-threading problems correctly describes this situation? A. Deadlock B. Starvation C. Livelock D. Race condition
  3. 3. Answer You’ve written an application for processing tasks. In this application, you’ve separated the critical or urgent tasks from the ones that are not critical or urgent. You’ve assigned high priority to critical or urgent tasks. In this application, you find that the tasks that are not critical or urgent are the ones that keep waiting for an unusually long time. Since critical or urgent tasks are high priority, they run most of the time. Which one of the following multi-threading problems correctly describes this situation? A. Deadlock B. Starvation C. Livelock D. Race condition
  4. 4. Explanation B . Starvation The situation in which low-priority threads keep waiting for a long time to acquire the lock and execute the code in critical sections is known as starvation. Starvation Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. Livelock A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. They're still blocking each other, so... Source: docs.oracle.com
  5. 5. Question Which of the following two definitions of Sync (when compiled in separate files) will compile without errors? A. class Sync { public synchronized void foo() {} } B. abstract class Sync { public synchronized void foo() {} } C. abstract class Sync { public abstract synchronized void foo(); } D. interface Sync { public synchronized void foo(); }
  6. 6. Answer Which of the following two definitions of Sync (when compiled in separate files) will compile without errors? A. class Sync { public synchronized void foo() {} } B. abstract class Sync { public synchronized void foo() {} } C. abstract class Sync { public abstract synchronized void foo(); } D. interface Sync { public synchronized void foo(); }
  7. 7. Explanation Abstract methods (in abstract classes or interfaces) cannot be declared synchronized , hence the options C and D are incorrect.
  8. 8. Question Which one of the following options correctly makes use of Callable that will compile without any errors? A. import java.util.concurrent.Callable; class CallableTask implements Callable { public int call() { System.out.println("In Callable.call()"); return 0; } } B. import java.util.concurrent.Callable; class CallableTask extends Callable { public Integer call() { System.out.println("In Callable.call()"); return 0; } } C. import java.util.concurrent.Callable; class CallableTask implements Callable<Integer> { public Integer call() { System.out.println("In Callable.call()"); return 0; } } D. import java.util.concurrent.Callable; class CallableTask implements Callable<Integer> { public void call(Integer i) { System.out.println("In Callable.call(i)"); } }
  9. 9. Answer Which one of the following options correctly makes use of Callable that will compile without any errors? A. import java.util.concurrent.Callable; class CallableTask implements Callable { public int call() { System.out.println("In Callable.call()"); return 0; } } B. import java.util.concurrent.Callable; class CallableTask extends Callable { public Integer call() { System.out.println("In Callable.call()"); return 0; } } C. import java.util.concurrent.Callable; class CallableTask implements Callable<Integer> { public Integer call() { System.out.println("In Callable.call()"); return 0; } } D. import java.util.concurrent.Callable; class CallableTask implements Callable<Integer> { public void call(Integer i) { System.out.println("In Callable.call(i)"); } }
  10. 10. Explanation C. The Callable interface is defined as follows: public interface Callable<V> { V call() throws Exception; } In option A), the call() method has the return type int , which is incompatible with the return type expected for overriding the call method and so will not compile. In option B), the extends keyword is used, which will result in a compiler (since Callable is an interface, the implements keyword should be used). In option D), the return type of call() is void and the call() method also takes a parameter of type Integer . Hence, the method declared in the interface Integer call() remains unimplemented in the CallableTask class, so the program will not compile.
  11. 11. Question Here is a class named PingPong that extends the Thread class. Which of the following PingPong class implementations correctly prints “ping” from the worker thread and then prints “pong” from the main thread? A. public static void main(String []args) { Thread pingPong = new PingPong(); System.out.print("pong"); } } B. public static void main(String []args) { Thread pingPong = new PingPong(); pingPong.run(); System.out.print("pong"); }} C. public static void main(String []args) { Thread pingPong = new PingPong(); pingPong.start(); System.out.println("pong"); }} D. public static void main(String []args) throws InterruptedException{ Thread pingPong = new PingPong(); pingPong.start(); pingPong.join(); System.out.println("pong"); }} class PingPong extends Thread { public void run() { System.out.println("ping "); }
  12. 12. Answer Here is a class named PingPong that extends the Thread class. Which of the following PingPong class implementations correctly prints “ping” from the worker thread and then prints “pong” from the main thread? A. public static void main(String []args) { Thread pingPong = new PingPong(); System.out.print("pong"); } } B. public static void main(String []args) { Thread pingPong = new PingPong(); pingPong.run(); System.out.print("pong"); }} C. public static void main(String []args) { Thread pingPong = new PingPong(); pingPong.start(); System.out.println("pong"); }} D. public static void main(String []args) throws InterruptedException{ Thread pingPong = new PingPong(); pingPong.start(); pingPong.join(); System.out.println("pong"); }} class PingPong extends Thread { public void run() { System.out.println("ping "); }
  13. 13. Explanation D . The main thread creates the worker thread and waits for it to complete (which prints “ping”). After that it prints “pong”. So, this implementation correctly prints “ping pong”. Why are the other options wrong? A. The main() method creates the worker thread, but doesn’t start it. So, the code given in this option only prints “pong”. B. The program always prints “ping pong”, but it is misleading. The code in this option directly calls the run() method instead of calling the start() method. So, this is a single threaded program: both “ping” and “pong” are printed from the main thread. C. The main thread and the worker thread execute independently without any coordination. (Note that it does not have a call to join() in the main method.) So, depending on which thread is scheduled first, you can get “ping pong” or “pong ping” printed.
  14. 14. Question Choose the correct option based on this program: class COWArrayListTest { public static void main(String []args) { ArrayList<Integer> aList = new CopyOnWriteArrayList<Integer>(); // LINE A aList.addAll(Arrays.asList(10, 20, 30, 40)); System.out.println(aList); } } A. When executed the program prints the following: [10, 20, 30, 40]. B. When executed the program prints the following: CopyOnWriteArrayList.class . C. The program does not compile and results in a compiler error in line marked with comment LINE A . D. When executed the program throws a runtime exception ConcurrentModificationException .
  15. 15. Answer Choose the correct option based on this program: class COWArrayListTest { public static void main(String []args) { ArrayList<Integer> aList = new CopyOnWriteArrayList<Integer>(); // LINE A aList.addAll(Arrays.asList(10, 20, 30, 40)); System.out.println(aList); } } A. When executed the program prints the following: [10, 20, 30, 40]. B. When executed the program prints the following: CopyOnWriteArrayList.class . C. The program does not compile and results in a compiler error in line marked with comment LINE A . D. When executed the program throws a runtime exception ConcurrentModificationException .
  16. 16. Explanation C . The program does not compile and results in a compiler error in the line marked with comment LINE A. The class CopyOnWriteArrayList does not inherit from ArrayList , so an attempt to assign a CopyOnWriteArrayList to an ArrayList reference will result in a compiler error. Note that the ArrayList suffix in the class named CopyOnWriteArrayList could be misleading as these two classes do not share anIS- A relationship.
  17. 17. Question What will this code segment print? public static void main(String []args) { List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); System.out.println(ints.parallelStream() .filter(i -> (i % 2) == 0).sequential() .isParallel()); } A. Prints 2 4 B. Prints false C. Prints true D. Cannot predict output
  18. 18. Answer What will this code segment print? public static void main(String []args) { List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); System.out.println(ints.parallelStream() .filter(i -> (i % 2) == 0).sequential() .isParallel()); } A. Prints 2 4 B. Prints false C. Prints true D. Cannot predict output
  19. 19. Explanation B. Prints false Though the created stream is a parallel stream, the call to the sequential() method has made the stream sequential. Hence, the call isParallel() prints false .
  20. 20. Question Which one of the following methods return a Future object? A. The overloaded replace() methods declared in the ConcurrentMap interface B. The newThread() method declared in the ThreadFactory interface C. The overloaded submit() methods declared in the ExecutorService interface D. The call() method declared in the Callable interface
  21. 21. Answer Which one of the following methods return a Future object? A. The overloaded replace() methods declared in the ConcurrentMap interface B. The newThread() method declared in the ThreadFactory interface C. The overloaded submit() methods declared in the ExecutorService interface D. The call() method declared in the Callable interface
  22. 22. Explanation C . The overloaded submit() methods declared in ExecutorService interface. The ExecutorService interface extends the Executor interface and provides services such as termination of threads and production of Future objects. Some tasks may take considerable execution time to complete. So, when you submit a task to the executor service, you get a Future object. A. The overloaded replace() methods declared in the ConcurrentMap interface remove an element from the map and return the success status (a Boolean value) or the removed value. B. The new Thread() is the only method declared in the ThreadFactory interface and it returns a Thread object as the return value D. The call() method declared in Callable interface returns the result of the task it executed.
  23. 23. Question In your application, there is a producer component that keeps adding new items to a fixed-size queue; the consumer component fetches items from that queue. If the queue is full, the producer has to wait for items to be fetched; if the queue is empty, the consumer has to wait for items to be added. Which one of the following utilities is suitable for synchronizing the common queue for concurrent use by a producer and consumer? A. ForkJoinPool B. Future C. Semaphore D. TimeUnit
  24. 24. Answer In your application, there is a producer component that keeps adding new items to a fixed-size queue; the consumer component fetches items from that queue. If the queue is full, the producer has to wait for items to be fetched; if the queue is empty, the consumer has to wait for items to be added. Which one of the following utilities is suitable for synchronizing the common queue for concurrent use by a producer and consumer? A. ForkJoinPool B. Future C. Semaphore D. TimeUnit
  25. 25. Explanation C. Semaphore The question is a classic producer–consumer problem that can be solved by using semaphores. The objects of the synchronizer class java.util.concurrent.Semaphore can be used to guard the common queue so that the producer and consumer can synchronize their access to the queue. Of the given options, semaphore is the only synchronizer ; other options are unrelated to providing synchronized access to a queue. A. ForkJoinPool provides help in running a ForkJoinTask in the context of the Fork/Join framework. B. Future represents the result of an asynchronous computation whose result will be “available in the future once the computation is complete.” D. TimeUnit is an enumeration that provides support for different time units such as milliseconds, seconds, and days.
  26. 26. Question What will this code segment print? class StringConcatenator { public static String result = ""; public static void concatStr(String str) { result = result + " " + str; } } class StringSplitAndConcatenate { public static void main(String []args) { String words[] = "the quick brown fox jumps over the lazy dog".split(" "); Arrays.stream(words).parallel().forEach(StringConcatenator::concatStr); System.out.println(StringConcatenator.result); } } A. over jumps lazy dog the brown fox quick the B. the quick brown fox jumps over the lazy dog C. Prints each word in new line D. Cannot predict output
  27. 27. Answer What will this code segment print? class StringConcatenator { public static String result = ""; public static void concatStr(String str) { result = result + " " + str; } } class StringSplitAndConcatenate { public static void main(String []args) { String words[] = "the quick brown fox jumps over the lazy dog".split(" "); Arrays.stream(words).parallel().forEach(StringConcatenator::concatStr); System.out.println(StringConcatenator.result); } } A. over jumps lazy dog the brown fox quick the B. the quick brown fox jumps over the lazy dog C. Prints each word in new line D. Cannot predict output
  28. 28. Explanation D. Cannot predict output When the stream is parallel, the task is split into multiple sub-tasks and different threads execute it. The calls to forEach(StringConcatenator::concatStr) now access the globally accessible variable result in StringConcatenator class. Hence it results in garbled output.
  29. 29. Question What is the expected output of this program when invoked as follows: java -ea AtomicIntegerTest static AtomicInteger ai = new AtomicInteger(10); public static void main(String []args) { ai.incrementAndGet(); ai.getAndDecrement(); ai.compareAndSet(10, 11); assert (ai.intValue() % 2) == 0; System.out.println(ai); } A. Prints 10 11 B. Prints 10 C. It crashes throwing an AssertionError D. Prints 9
  30. 30. Answer What is the expected output of this program when invoked as follows: java -ea AtomicIntegerTest static AtomicInteger ai = new AtomicInteger(10); public static void main(String []args) { ai.incrementAndGet(); ai.getAndDecrement(); ai.compareAndSet(10, 11); assert (ai.intValue() % 2) == 0; System.out.println(ai); } A. Prints 10 11 B. Prints 10 C. It crashes throwing an AssertionError D. Prints 9
  31. 31. Explanation C. It crashes throwing an AssertionError . The initial value of AtomicInteger is 10. Its value is incremented by 1 after calling incrementAndGet (). After that, its value is decremented by 1 after calling getAndDecrement ( ). The method compareAndSet (10, 11) checks if the current value is 10, and if so sets the atomic integer variable to value 11. Since the assert statement checks if the atomic integer value % 2 is zero (that is, checks if it is an even number), the assert fails and the program results in an AssertionError .
  32. 32. Question Consider that you are developing an cards game where a person starts the game and waits for the other players to join. Minimum 4 players are required to start the game and as soon as all the players are available the game has to get started. For developing such kind of game application which of the following synchronization technique would be ideal: A. Semaphore B. Exchanger C. Runnable D. Cyclic Barrier
  33. 33. Answer Consider that you are developing an cards game where a person starts the game and waits for the other players to join. Minimum 4 players are required to start the game and as soon as all the players are available the game has to get started. For developing such kind of game application which of the following synchronization technique would be ideal: A. Semaphore B. Exchanger C. Runnable D. Cyclic Barrier
  34. 34. Explanation D. CyclicBarrier CyclicBarrier helps provide a synchronization point where threads may need to wait at a predefined execution point until all other threads reach that point. A. A Semaphore controls access to shared resources. A semaphore maintains a counter to specify number of resources that the semaphore controls B. The Exchanger class is meant for exchanging data between two threads. This class is useful when two threads need to synchronize between each other and continuously exchange data. C. Runnable is an interface used in creating threads
  35. 35. Question Consider the following program and choose the correct option describing its behavior class PingPong extends Thread { public void run() { System.out.print("ping "); throw new IllegalStateException(); } public static void main(String []args) throws InterruptedException { Thread pingPong = new PingPong(); pingPong.start(); System.out.print("pong"); } } A. This program results in a compiler error. B. Prints the ping pong and exception in any order C. This program throws a runtime error. D. Prints pong ping
  36. 36. Answer Consider the following program and choose the correct option describing its behavior class PingPong extends Thread { public void run() { System.out.print("ping "); throw new IllegalStateException(); } public static void main(String []args) throws InterruptedException { Thread pingPong = new PingPong(); pingPong.start(); System.out.print("pong"); } } A. This program results in a compiler error. B. Prints the ping pong and exception in any order C. This program throws a runtime error. D. Prints pong ping
  37. 37. Explanation B. Prints the ping pong and exception in any order The programs executes fine and the exact output cannot be predicted as the main thread and the worker thread execute independently without any coordination.
  38. 38. Question Consider the following program and choose the correct option describing its behavior public static void main(String[] args) { ExecutorService executor; try(executor = Executors.newFixedThreadPool(5)){ Runnable worker = new Runnable() { public void run() { System.out.print("Hello"); } }; executor.execute(worker); executor.shutdown(); System.out.println("Execution completed"); } } A. This program results in a compiler error. B. Prints Execution completed and Hello in next line C. Prints Hello D. Prints Execution completed
  39. 39. Answer Consider the following program and choose the correct option describing its behavior public static void main(String[] args) { ExecutorService executor; try(executor = Executors.newFixedThreadPool(5)){ Runnable worker = new Runnable() { public void run() { System.out.print("Hello"); } }; executor.execute(worker); executor.shutdown(); System.out.println("Execution completed"); } } A. This program results in a compiler error. B. Prints Execution completed and Hello in next line C. Prints Hello D. Prints Execution completed
  40. 40. Explanation A. This program results in a compiler error Try-with-resources statement cannot be used here as, ExecutorServices does not implement java.lang.AutoCloseable interface
  41. 41. Upcoming Workshops/Bootcamps • SOLID Principles and Design Patterns – Aug 27th • Microsoft Azure Bootcamp – Aug 27th • Modern Software Architecture – Sep 10th Please visit CodeOps.tech for more details such as agenda/cost/trainer and registration. OCP Java: http://ocpjava.wordpress.com
  42. 42. Tech talks  Tech talks are for knowledge sharing - so there is no cost associated with it  We usually share the presentation & supporting material to the participants after the tech talk  Duration of the tech talk would be for 1 hour and will be given at your office premises  Topics on which we offer tech talks can be found here Tech Talk Topics  We also offer free workshop on Introduction to Docker which will be a hands-on session
  43. 43. Meetups • Core-Java-Meetup-Bangalore • Software-Craftsmanship-Bangalore – 20th July @Ginserv • Container-Developers-Meetup - 20th Aug @Avaya • CloudOps-Meetup-Bangalore - 20th Aug @Avaya • JavaScript-Meetup-Bangalore - 20th Aug • Technical-Writers-Meetup-Bangalore – 25th Sep • Software Architects Bangalore – 1st Oct @Prowareness • Bangalore-SDN-IoT-NetworkVirtualization-Enthusiasts
  44. 44. Founders Achievements www.codeops.tech slideshare.net/codeops reachus@codeops.tech linkedin.com/codeops  Has 14+ years of corporate experience and worked in various roles and conducted many corporate trainings  Authored/co-authored many articles, research papers, and books that got internationally published and respected in the community  Have Software Engineering Certified Instructor (SECI) and Professional Software Engineering Master (PSEM) certifications from IEEE

×