Return to site

☕🎓JAVA CERTIFICATION QUESTION: Cyclic Barrier

· ocp,java

Given the following class:

 

What is the result? Choose one.

* Nothing is printed.

* Only tasks 1 and 2 execute in arbitrary order.

* Only tasks 1, 2, and 3 execute in arbitrary order.

* Only tasks 1 through 9 execute in arbitrary order.

* All tasks execute in arbitrary order.

Answer: Nothing is printed

This code uses the rangeClosed method of the IntStream class.

rangeClosed(int startInclusive, int endInclusive) returns a sequential ordered IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.

These 10 numbers are used to build tasks described by the Task class.

The tasks all share a single CyclicBarrier, and each task is passed to the executor service for execution.

In the question, the code uses a thread pool that has two threads and a CyclicBarrier initialized with an argument value of 3.

CyclicBarrier is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

CyclicBarriers are useful in programs involving a fixed-sized party of threads that must occasionally wait for each other.

The barrier is called cyclic because it can be re-used after the waiting threads are released.

await() waits until all parties have invoked await on this barrier.

In this quiz’s code, there are exactly two threads in the pool.

This means that only two tasks can be in process at any one instant.

Note that tasks that are blocked in methods such as await are still in process.

Therefore, the code has asked the pool to execute 10 tasks, but it gave the pool only two threads, so only two tasks can be in process at one time.

As soon as the first two tasks have been called await, their execution is on hold.

The tasks are in process but waiting for the cyclic barrier to reach the three awaiting threads to be able to release them.

Because the pool only has two threads, no threads are available to execute a third task, and the release can never be done.

Next, consider the shutdown() method.

This waits until all the in-process tasks are completed, but the two tasks that are waiting for that release to be done will never continue executing, and they will never be complete.

This also means that the other eight tasks never even start. Because of this, the program never ends, and no output is ever printed.