Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/synchronized-static-method-and-threads-in-java
Question 215 / 297:  What is the possible output of running this program once as it is and once by marking swim() synchronized?
Choose 3
class Swimmer implements Runnable{

String name ;

Swimmer(String name){

this.name = name;

}

public void run() {

Test.swim(name);

}

}

public class Test {

public static void swim(String name) {

System.out.print(name);

System.out.print(name);

}

public static void main(String[] args) {

new Thread(new Swimmer("Tom")).start();

new Thread(new Swimmer("Hanks")).start();

}

}

<< First < Previous Next > Last >>
Explanation:

Pay attention to the fact that swim() is a static method, which means there is only one instance of this method for all Test objects.

When running the program as it is, two threads -when started- are competing to enter method swim(), we cannot determine which thread will enter the method first. Since swim() is not synchronized, it means the running thread doesn't seize the lock of Test class, meaning it is possible that the thread doesn't finish executing swim() and waits for its next CPU slice to return back and continue executing, and while waiting there the other thread(s) can enter swim().

Another possibility is that the entering thread finishes executing swim() before even the second thread get started.

By synchronizing swim(), the entering thread seizes the lock of class Test, and it doesn't release the lock until it finishes executing swim(), therefore alternating between threads to execute swim() is out of question.

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
David Bourgeois
Start Quiz
Anindyo Mukhopadhyay
Start Quiz
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>