Zhiwei Huang

Greenhorn
+ Follow
since Jul 06, 2010
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Zhiwei Huang

Jim Hoglund wrote:One use is to hold code that you want to run immediately when the class is loaded,
before any objects are instantiated. For an inheritance tree, this means that the
order of execution of the static blocks is from subclass on up. (Execution of any
non-static blocks is from superclass on down.) How is this useful? I'd just say,
very special situations.

Jim ... ...



So if I have

the output would be BA?

Abimaran Kugathasan wrote:

Zhiwei Huang wrote:
my bad. the static flag is set to 0 instead of 9 when initialized.
Thus as d is static, the two threads are calling the same chat method on same instance, as the explanation on K&B's book says, they cannot swap back and forth... so the answer should be only F...



This is NOT fair. When I answered the question, the variable flag is set to 9. You've changed it to 0. If it is 9, the possible answer are E and E.

Because, now it is 9, the only answer is F.

When you EDIT the code, after some one has answered, it's better to put the reason to EDIT, otherwise it'll be ODD.


That's why I said it's MY BAD and thanks for reminding me the EDIT part.

Abimaran Kugathasan wrote:Welcome to JavaRanch! QuoteYourSources when you ask question.

E, F are the correct answer. Remember in DudesChat class you have a static variable d. So think about that.


Got it? If not ask!



my bad. the static flag is set to 0 instead of 9 when initialized.
Thus as d is static, the two threads are calling the same chat method on same instance, as the explanation on K&B's book says, they cannot swap back and forth... so the answer should be only F...


And given these two fragments:


When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the ouput could be yo dude dude yo
E. With fragment I, the output could be dude dude yo yo
F. With fragment II, the output could be yo dude dude yo

The Official Answer is F, but in my opinion as flag is a static variable, even if instance method chat is marked synchronized, flag could still be "touched" by other thread. Actually when I run this code on my machine multiple times, I never saw D and F, and E always happens. Could someone give me any explanation?