Tuesday, May 7, 2024
HomeJavaQuiz your self: Crossing Java’s CyclicBarrier in a multithreaded atmosphere

Quiz your self: Crossing Java’s CyclicBarrier in a multithreaded atmosphere


Oracle Java Certification, Core Java, Oracle Java Learning, Java Prep, Oracle Java Learning, Oracle Java Quiz

Given the next class

public class Escape {

  static class Activity implements Runnable {

    int i;

    CyclicBarrier cb;

    public Activity(int i, CyclicBarrier cb) {this.i=i; this.cb=cb;}

    @Override

    public void run() {

      strive {

        cb.await();

      } catch (Exception e) {}

      System.out.printf(“Activity %d executedpercentn”, i);

    }

  }

  public static void fundamental(String[] args) {

    ultimate ExecutorService es = Executors.newFixedThreadPool(2);

    ultimate CyclicBarrier cb = new CyclicBarrier(3);

    IntStream

      .rangeClosed(1, 10)

      .mapToObj(i -> new Activity(i, cb))

      .forEach(t -> es.execute(t));

    es.shutdown();

  }

}

What’s the end result? Select one.

A. Nothing is printed.

B. Solely duties 1 and a couple of execute in arbitrary order.

C. Solely duties 1, 2, and three execute in arbitrary order.

D. Solely duties 1 by means of 9 execute in arbitrary order.

E. All duties execute in arbitrary order.

Reply. As typically occurs with examination questions, the complexity of this code disguises the relative simplicity of the answer. Recognizing the factor that actually issues to resolve the query shortly is mostly a manifestation of debugging ability. As such, it’s not a trick query, however it may possibly definitely be a little bit irritating if you happen to miss the important thing level. By no means spend too lengthy on one query till you’ve answered all of the others—however we’ve made that time earlier than.

This code makes use of the rangeClosed technique of the IntStream class. This technique produces a sequence of monotonically growing int values beginning with the primary argument worth and ending with the second argument worth; which means 1 by means of 10 on this case. (If as a substitute the vary technique had been used, the second argument would behave as a fence worth; that’s, the vary produced would cease wanting that second argument’s worth.)

These 10 numbers are used to construct duties described by the Activity class. The duties all share a single CyclicBarrier, and every job is handed to the executor service for execution.

Within the query, the code makes use of a thread pool that has two threads and a CyclicBarrier initialized with an argument worth of three.

The conduct of the CyclicBarrier could also be regarded as a door with a deal with. On this instance, the door deal with should be turned 3 times to open the door (that’s because of the argument of three within the constructor of the CyclicBarrier). The await technique turns the door deal with when it’s known as. If a name is just not the third name to await, the calling thread stops executing till different threads name await once more, and on the third name the door opens. When the door opens, these three threads proceed executing—they cross by means of the door, to proceed this analogy—and the door closes behind them. Additional threads calling await will once more be made to attend, till one other three calls to await have been made. This course of continues; that’s why the CyclicBarrier is cyclic.

On this quiz’s code, there are precisely two threads within the pool. Which means solely two duties might be in course of at anybody prompt. Notice that duties which can be blocked in strategies comparable to await are nonetheless in course of. Subsequently, the code has requested the pool to execute 10 duties, however it gave the pool solely two threads, so solely two duties might be in course of at one time. As quickly as the primary two duties have known as await, their execution is on maintain. The duties are in course of however ready for the door to open. As a result of the pool solely has two threads, no threads can be found to execute a 3rd job, and the door deal with can by no means be turned for the essential third time. The system merely stops proper there, by no means to make any extra progress. Additionally notice that at this level, no output has been generated.

Subsequent, think about the shutdown() technique. This waits till all of the in-process duties are accomplished, however the two duties which can be ready for that door to open won’t ever proceed executing, and they’re going to by no means be full. This additionally signifies that the opposite eight duties by no means even begin. Due to this, this system by no means ends, and no output is ever printed. This makes possibility An accurate and choices B, C, D, and E incorrect.

To grasp how this works, think about some variant eventualities.

Suppose you created three threads within the pool with Executors.newFixedThreadPool(3). On this state of affairs, three duties might be in course of, and they’re going to have the ability to name await the required 3 times. At that time, the primary three duties will transfer on and print the “Activity executed” message. After these first three duties are accomplished, the threads from the pool will develop into out there and can choose up the subsequent duties, that are duties 4, 5, and 6. These too will then have the ability to execute the await technique 3 times, print their message, and end. Then duties 7, 8, and 9 will proceed to completion too. Sadly, the tenth job will probably be caught, as there is not going to be the required extra two calls to await to permit it to be accomplished. Discover that on this situation, the issue is that no job exists to make the decision, not that there are not any threads to run the duties. However the backside line is that job 10 would by no means print its message, and this system will nonetheless by no means terminate.

One other potential change can be to have two threads with Executors.newFixedThreadPool(2) and require two calls to await with new CyclicBarrier(2) as a substitute of three calls. On this case, the duties end in teams of two as a result of you’ll want to flip the door deal with solely twice to open the door. Consequently, all 10 duties can be accomplished, every printing its message. In spite of everything 10 have been accomplished, this system would shut down.

One ultimate level: When three threads have known as the await technique, there’s no explicit expectation that they may resume executing in the identical order wherein they arrived on the await technique. Even when they did, the working system’s thread scheduling might arbitrarily maintain one up whereas letting one other run freely, in order that their relative arrival instances on the printf assertion would nonetheless not be predictable. Due to this, any output from the teams of two or three threads within the two different eventualities should be assumed to be printed in arbitrary order.

Conclusion. The right reply is possibility A.

Supply: oracle.com

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments