Return to site

☕🎓JAVA CERTIFICATION QUESTION: Multithreading and the Java keyword synchronized

👉The goal is to obtain consistent results and avoid unwanted effects.

· java,ocp

Imagine that you are working with multiple instances of the following SyncMe class, and the instances are used by multiple Java threads:

What statements are true about the class? Choose two.

* Concurrent calls to the hi() methods can sometimes print hi hi.

* Concurrent calls to the bye() methods can sometimes print bye bye.

* Concurrent calls to the meet() method always print hi there! bye there!.

* Concurrent calls to the meet() method can print bye bye.

* Concurrent calls to the meet() method can print hi hi.

#java #certificationquestion #ocp

Answer:

"concurrent calls to the bye() methods can sometimes print bye bye."

and

"concurrent calls to the meet() method can print bye bye."

Given this discussion and noting that the hi() method is static but the other two are instance methods, and also that the question states that multiple objects exist, recognize that only one thread at a time can be executing the hi() method, but more than one thread might be executing the other two methods.

That tells you that whenever hi has been printed, another hi cannot be printed until after the printing of there!

Using the same logic as above, concurrent calls to meet() cannot result in hi hi being printed either.

By contrast, concurrent calls to the bye() method can execute concurrently if they are invoked on different instances of the class.

In such a situation the output of the two invocations can become interleaved, and you might in fact see bye bye printed.