Return to site

☕🎓JAVA CERTIFICATION QUESTION: Handling side effects in Java

· java,ocp

Imagine that your colleague is prototyping new business logic that must work in a multithreaded application and has created the following class:

To test the class, your colleague wrote the following method and then invoked the method, passing a Stream object containing two MyRunnable instances:

Which statement is correct? Choose one.

* The output will be exactly hello bye hello bye.

* The output will always start with hello followed by either hello or bye.

* No output will be produced.

* None of the above.

#java #certificationquestion #ocp

Answer: None of the above.

The real topic of the question is not multithreading but the Stream API, and especially the count() method.

The documentation for the count() method states the following:

An implementation may choose to not execute the stream pipeline (either sequentially or in parallel)

if it is capable of computing the count directly from the stream source.

In such cases no source elements will be traversed and no intermediate operations will be evaluated.

Behavioral parameters with side-effects, which are strongly discouraged except for harmless cases such as debugging, may be affected.

The stream does only a simple map, the count can be computed directly; so the map will be bypassed and no outputs would be produced.

If, however, the argument stream has a size that is not known until it runs, some output will be produced.

So, "none of the above" is the right answer.

(if there was some Randomness in the stream, there would have been outputs)