java concurrency questions and answers

44
Quiz Fun way to learn more Java Concurrency

Upload: bangalore-container-conference-2017

Post on 16-Apr-2017

798 views

Category:

Technology


6 download

TRANSCRIPT

Page 1: Java concurrency questions and answers

QuizFun way to learn more

Java Concurrency

Page 2: Java concurrency questions and answers

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. DeadlockB. StarvationC. LivelockD. Race condition

Page 3: Java concurrency questions and answers

AnswerYou’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. DeadlockB. StarvationC. LivelockD. Race condition

Page 4: Java concurrency questions and answers

ExplanationB . StarvationThe 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.StarvationStarvation 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.

LivelockA 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

Page 5: Java concurrency questions and answers

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();}

Page 6: Java concurrency questions and answers

AnswerWhich 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();}

Page 7: Java concurrency questions and answers

ExplanationAbstract methods (in abstract classes or interfaces) cannot be declared synchronized , hence the options C and D are incorrect.

Page 8: Java concurrency questions and answers

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)"); }}

Page 9: Java concurrency questions and answers

AnswerWhich 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)"); }}

Page 10: Java concurrency questions and answers

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

Page 11: Java concurrency questions and answers

Question Here is a class named PingPong that extends the Thread class. Which of thefollowing PingPong class implementations correctly prints “ping” from theworker 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 "); }

Page 12: Java concurrency questions and answers

AnswerHere is a class named PingPong that extends the Thread class. Which of thefollowing PingPong class implementations correctly prints “ping” from theworker 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 "); }

Page 13: Java concurrency questions and answers

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

Page 14: Java concurrency questions and answers

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 .

Page 15: Java concurrency questions and answers

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

Page 16: Java concurrency questions and answers

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

Page 17: Java concurrency questions and answers

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 4B. Prints falseC. Prints trueD. Cannot predict output

Page 18: Java concurrency questions and answers

AnswerWhat 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 4B. Prints falseC. Prints trueD. Cannot predict output

Page 19: Java concurrency questions and answers

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

Page 20: Java concurrency questions and answers

Question Which one of the following methods return a Future object?

A. The overloaded replace() methods declared in the ConcurrentMap interfaceB. The newThread() method declared in the ThreadFactory interfaceC. The overloaded submit() methods declared in the ExecutorService interfaceD. The call() method declared in the Callable interface

Page 21: Java concurrency questions and answers

AnswerWhich one of the following methods return a Future object?

A. The overloaded replace() methods declared in the ConcurrentMap interfaceB. The newThread() method declared in the ThreadFactory interfaceC. The overloaded submit() methods declared in the ExecutorService interfaceD. The call() method declared in the Callable interface

Page 22: Java concurrency questions and answers

ExplanationC . The overloaded submit() methods declared in ExecutorService interface. The ExecutorService interface extends the Executor interface and provides services such astermination of threads and production of Future objects. Some tasks may take considerable execution timeto 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.

Page 23: Java concurrency questions and answers

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. ForkJoinPoolB. FutureC. SemaphoreD. TimeUnit

Page 24: Java concurrency questions and answers

AnswerIn 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. ForkJoinPoolB. FutureC. SemaphoreD. TimeUnit

Page 25: Java concurrency questions and answers

ExplanationC. 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 onlysynchronizer ; 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.

Page 26: Java concurrency questions and answers

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 theB. the quick brown fox jumps over the lazy dogC. Prints each word in new lineD. Cannot predict output

Page 27: Java concurrency questions and answers

AnswerWhat 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 theB. the quick brown fox jumps over the lazy dogC. Prints each word in new lineD. Cannot predict output

Page 28: Java concurrency questions and answers

ExplanationD. 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 resultin StringConcatenator class. Hence it results in garbled output.

Page 29: Java concurrency questions and answers

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 11B. Prints 10C. It crashes throwing an AssertionErrorD. Prints 9

Page 30: Java concurrency questions and answers

AnswerWhat 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 11B. Prints 10C. It crashes throwing an AssertionErrorD. Prints 9

Page 31: Java concurrency questions and answers

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

Page 32: Java concurrency questions and answers

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. SemaphoreB. ExchangerC. RunnableD. Cyclic Barrier

Page 33: Java concurrency questions and answers

AnswerConsider 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. SemaphoreB. ExchangerC. RunnableD. Cyclic Barrier

Page 34: Java concurrency questions and answers

ExplanationD. 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 controlsB. 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 continuouslyexchange data.C. Runnable is an interface used in creating threads

Page 35: Java concurrency questions and answers

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 orderC. This program throws a runtime error.D. Prints pong ping

Page 36: Java concurrency questions and answers

AnswerConsider 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 orderC. This program throws a runtime error.D. Prints pong ping

Page 37: Java concurrency questions and answers

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

Page 38: Java concurrency questions and answers

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 lineC. Prints HelloD. Prints Execution completed

Page 39: Java concurrency questions and answers

AnswerConsider 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 lineC. Prints HelloD. Prints Execution completed

Page 40: Java concurrency questions and answers

ExplanationA. This program results in a compiler error

Try-with-resources statement cannot be used here as, ExecutorServices does not implement java.lang.AutoCloseable interface

Page 41: Java concurrency questions and answers

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

Page 42: Java concurrency questions and answers

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

Page 43: Java concurrency questions and answers

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

Page 44: Java concurrency questions and answers

Founders Achievements

www.codeops.tech slideshare.net/codeops

[email protected] 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