Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
If main acquires the monitor first, it will start waiting (don't forger that wait releases the monitor).
When the thread acquires the monitor, it will notify main and release him from the wait.
On the other hand, if the Thread acquires the monitor first, then it will call notifyAll() before main even starts wait()ing. When the thread releases the monitor, main will start wait()ing forever and never get to print the result.
try inserting the code
Thread.currentThread().sleep(10000);
right after the line job.start() in main to demonstrate this.
@Avinash the code is very much valid, just put the code inside one class.
This program actually does not go into infinite waiting if you run in your IDE.
But try to debug it by putting break point in the 1st line of main method and try to step over each line. It stops at job.wait(); and goes infinite loops.
Then if you suspend the thread and resume again, it will execute the run method and prints the output with the below error message.
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]
The parenthesis were missing , The correct running code is below , and it does print the output : 100000
class Job extends Thread {
private int counter;
@Override
public void run() {
synchronized(this) {
for(int i = 0; i < 100000; i++)
counter++;
this.notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Job job = new Job();
job.start();
synchronized(job) {
job.wait();
}
System.out.println(job.counter);
}
}
Agreed with Anon & TD...
Try to execute below code , it will go in infinite wait..
class Job extends Thread {
private int counter;
@Override
public void run() {
synchronized(this) {
for(int i = 0; i < 100000; i++)
counter++;
this.notifyAll();
System.out.println("Completed Counting......");
}
}
public static void main(String[] args) throws InterruptedException {
Job job = new Job();
job.start();
Thread.sleep(10000);
System.out.println("Waiting to get End.....");
synchronized(job) {
job.wait();
}
System.out.println(job.counter);
}
}
if job thread executes first and calls notifyAll() method before main thread calls wait() then it will be in infinite waiting ..
- TD June 02, 2013but it is not guranteed which thread will excute first so when you are running locally you are getting output...
if you want put main() in infinite loop then call sleep(10 secs) method in main thread.