• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why interruption here is ignored always when solving SCJP Thread questions

 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Waiting2 implements Runnable {
int state;
public synchronized void run() {
if (state++ < 3) {
System.out.print(" " + Thread.currentThread().getId());

//No interruptions really happen for exam purposes.
//During real SCJP Thread questions, always ignore what's in catch()

try { this.wait(); } catch (Exception e) { }
System.out.print(" " + Thread.currentThread().getId());
}

else {
try { Thread.sleep(2000); } catch (Exception e) { }
notify();
notifyAll();
}
}
public static void main(String [] args) {
Waiting2 w = new Waiting2();
new Thread(w).start();
new Thread(w).start();
new Thread(w).start();
new Thread(w).start();
}
}


What�s a possible result? (choose all that apply)

A) 6 7 8 9
B) 6 7 8 6
C) 6 7 8 6 7 8
D) 6 7 8 6 7 9
E) 6 7 8 8 6 7
F) 6 7 8 6 6 7 8
G) 6 7 8 9 6 7 8 9
H) 6
I) 6 6
J) else block is never reached because of wait()

Why answer is C and E and not H, I, J ?

I just thought synchronization works and doesn't allow 2 threads in to enter at same time so the answer should be 6 or (6 6 if an exception is thrown). But SUN doesn't even want me to consider exceptions to occur when asking questions about threads.
[ June 09, 2006: Message edited by: Firas Zureikat ]
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
where is the 6, 7, 8 coming from?
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, for the 6 6 it's coming from:

System.out.print(" " + Thread.currentThread().getId()); // Line 1
try { this.wait(); } catch (Exception e) { }
System.out.print(" " + Thread.currentThread().getId()); // Line 2

So Line 1 prints 6 ones (assuming the current thread's ID is 6) and then Line 2 prints 6 again because the is just a copy of Line 1.
 
luo luo
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ignore my previous post getId() will return the identifier for a thread, which won't change for the life time of thread. You can reuse it after only after the thread is dead.

As per your question. Because the four threads are working on only one instance of the object, there's only one lock for all the threads. suppose the id is a, b, c, d separately. Then the output would have the following pattern:

a b c x1 x2 x3

x will be one of a b c
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But because there is only 1 lock for all threads (as you said above) and with synchronization allowing only one thread to enter at a time, when
"try { this.wait(); }"
is reached, the first thread that enters would wait forever.

So the pattern is

x
where x is one of a, b, c or d

Right? But this logic is not matching the correct answer (where notifyAll() is assumed to be reached), why?

Other questions:

Q1) Does wait() release the lock?
Q2) If an exception occurs for wait() above, does this result in exiting the program or just just result in control flow going to the next statement that follows (i.e. printing Current Thread's ID)?
[ June 09, 2006: Message edited by: Firas Zureikat ]
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


1. When Waiting2 instance is created, value of state is initialized to zero.

2. At line 1, run method will be executed. state++ will increment the value of state to 1, but the value of expression state++ is zero < 3, prints 6 and comes in waiting state.

3. At line 2, second thread starts run method. state++ will increment the value of state to 2, but the value of expression state++ is still 1 < 3, prints 7 and then second thread comes in waiting state.

3. At line 3, third thread starts run method. state++ will increment the value of state to 3, but the value of expression state++ is still 2 < 3, prints 8 and then third thread comes in waiting state.

4. At line 4, fourth thread starts run method. state++ will increment the value of state to 4, but the value of expression state++ is still 3 < 3 false, so it executes else part, sleeps for 2 second and then it notifies.

Either it notify first id 6 thread or id 7 thread or id 8 thread. So u could hav three options.

Upto this point output will be....

6 7 8 6
or
6 7 8 7
or
6 7 8 8

wen id 9 thread calls notifyAll(), then remaining two thread will wake up.

Therefore output could be....

1. for 6 7 8 6
--------------
6 7 8 6 7 8
6 7 8 6 8 7



2. for 6 7 8 7
---------------
6 7 8 7 6 8
6 7 8 7 8 6



3. for 6 7 8 8
---------------
6 7 8 8 6 7
6 7 8 8 7 6
---------------


With given option, only C and E is correct.


Hope this will sort out ur remaining problems.


regards


Naseem
[ June 09, 2006: Message edited by: Naseem Khan ]
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Naseem,

I appreciate very much your detailed explanation. I get it now.

For SCJP purposes, I feel that the catch() blocks that SUN puts in the Thread questions are not meant to be considered in determining the possible result like the question above. Unless it's a syntax question then this rule doesn't apply (ofcourse wait() has to be in a try block).

I mean you can't assume that there is an interrruption (like hitting Ctr + x on the keyboard) and following the catch flow above that would lead to printing the interrupted thread's ID instead of really waiting for notify and then printing as Naseem explained.

So in the SCJP, if there is a catch block like above and the question asks what's the possible result like above, you should never assume an interruption takes place, which leads to the print statement after the catch clause and print an ID as a "possible result". So the 6 6 choice is never NEVER true because wait() is never NEVER ever interrupted for the purpose of the exam, right?

Thanks I understand what you explained at least.

So what's the possible result for the following:

--------------------------------------------------------------------------
class Waiting2 implements Runnable {
int state;
public synchronized void run() {
if (state++ < 2) {
System.out.print(" " + Thread.currentThread().getId());

//No interruptions really happen for exam purposes.
//During real SCJP Thread questions, always ignore what's in catch()

try { this.wait(); } catch (Exception e) {System.out.print(" Never reached "); }
System.out.print(" " + Thread.currentThread().getId());
}

else {
try { Thread.sleep(2000); } catch (Exception e) {System.out.print(" Never reached "); }
notifyAll();
}
}
public static void main(String [] args) {
Waiting2 InterruptMe = new Waiting2();
new Thread(InterruptMe).start();
new Thread(InterruptMe).start();
}
}

Possible Result: (choose all possibilities)
A) 6 6
B) 6 7 6
C) 6 Never reached 6
D) 6 Never reached 6 7 Never reached 7
E) Compile error (else block never unreachable)
F) Other
[ June 10, 2006: Message edited by: Firas Zureikat ]
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q1) Does wait() release the lock?


Yup, wait() releases lock that current thread have own.


As in your given code snipplet four threads are created.
Once first thread entered inside the run() method no other thread are allowed to enter but at the time of calling wait() on current thread, current thread will release lock so other thread will fight to enter inside the run method and one that wins will be enter inside the run method and once it will reaches to line this.wait() it will release lock and other two are allowed to enter as so on.. .




-Amit Goyal
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your latest code, only two threads are getting created.

1) For the first thread entering run(), state is 0. 0 < 2 is true. So, this thread goes to wait state after printing its id, say 6 (state is incremented to 1)

2) For the second thread entering run(), state is 1. 1 < 2 is true. So, this thread also goes to wait state after printing its id, say 7

For these two threads to come out of the wait state, some other thread needs to notify them. But, there is no other thread to perform this task. So, after printing 6 7, the program will wait forever.

So, the answer is Other
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ashish u r rite.

Answer is other.

But u never know with wat id it starting. I run this program on j2sdk 1.5 and my output is 7 8 and program wait forever.


Originally posted by Firas Zureikat

For SCJP purposes, I feel that the catch() blocks that SUN puts in the Thread questions are not meant to be considered in determining the possible result like the question above. Unless it's a syntax question then this rule doesn't apply (ofcourse wait() has to be in a try block).

I mean you can't assume that there is an interrruption (like hitting Ctr + x on the keyboard) and following the catch flow above that would lead to printing the interrupted thread's ID instead of really waiting for notify and then printing as Naseem explained.

So in the SCJP, if there is a catch block like above and the question asks what's the possible result like above, you should never assume an interruption takes place, which leads to the print statement after the catch clause and print an ID as a "possible result". So the 6 6 choice is never NEVER true because wait() is never NEVER ever interrupted for the purpose of the exam, right?



Yes u r rite...

With any scheduling method like sleep, yield or wait in try block, thread simply returns from it without throwing ny exception wen time expires in sleep or some other thread notifies it in case of wait, so catch will never be executed.

regards
[ June 10, 2006: Message edited by: Naseem Khan ]
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, thanks..

Doesn't notify() in original code notify the thread that was waiting the longest?
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not sure whether it will notify the thread which is waiting longest or second one.

Frm output it seems that it could be ny one. Either 6 or 7 or 8.


from C--->>>6 7 8 6 7 8 it notifies first id 6 thread (longest waiting thread)

from E--->>>6 7 8 8 6 7 it notifies 8th id thread.


NOT NECESSARILY LONGEST WAITING THREAD


regards

Naseem.K

[ June 10, 2006: Message edited by: Naseem Khan ]
[ June 10, 2006: Message edited by: Naseem Khan ]
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In first code, if u jst remove notify() and notifyAll() method, wen id 9 thread executes else part and simply returns frm it (without calling notify or notifyAll() method), still other waiting thread will wakeup.

here run() method will perform a sort of cleanup operation.
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In original code, if I comment out notify() and notifyAll(), my JVM waits after printing 9 as follows:

C:\myJava\source>java Waiting2
7 8 9

As for which thread is notified, when I only put back the notify() (uncomment it), my the JVM waits after it prints 7 8 9 7.

Doesn't notfify() notify the thread that waits the longest?. Since the start() on each Thread instance isn't guarnanteed to create a thread in the order listed in original code, there is no way to know which one would be notified. But in my case, it's always the same sequence: 7 8 9 7 when only notify() is there. The 7 waited the longest so it gets notified "always" before the others so it prints 7.

[ June 10, 2006: Message edited by: Firas Zureikat ]
[ June 11, 2006: Message edited by: Firas Zureikat ]
 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Naseem I just want to ask that Shouldn't it give Illegal thread state exception as we are calling start() method more than once on the same object.

I have got this in one of the mock exams I am taking...
 
Ashish Laddha
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IllegalThreadStateException will come into picture when you are trying to call start() on the same thread more than once.

Following code will throw up IllegalThreadStateException
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic