Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Non synchronized threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Non synchronized threads" Watch "Non synchronized threads" New topic

Non synchronized threads

Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
The code is taken directly from Dr. K's book. Mutex class creates two threads: Pusher and Popper.

The output of the code is:
Exit from main().
Pushed: true
Popped: null
What I can't understand is why is popped null. First, I thought maybe because the JVM did a context switch in the middle of incrementing toOfStack, but then I put in System.out statements and there was no context switch during ++topOfStack.

Here is the code:
Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
the smiley face shouldn't be there:
the for loop is an infinite loop.
siddharth chhabra

Joined: Mar 04, 2004
Posts: 4
I think after the ++topOfStack; since you have a thread.sleep ...the object on top of stack is still null

in the meanwhile the pop executes and assigns null to the obj which gets printed in your code

I agree. Here's the link:
subject: Non synchronized threads
It's not a secret anymore!