"I'm not back." - Bill Harding, Twister
Originally posted by Jim Yingst:
The code will be synchronized in either case, in the sense that the code uses synchronized blocks to acquire locks, as you can see from looking at the code. However if the two MyThread instances are synchronized on two different String instances (two different values of s) then the synchronization will have no significant effect - the two method calls may run concurrently. But if the two MyThread instances are synchronized on the same String instance, then the two run() methods may not run concurrently. Or more precisely, the synchronized blocks within the run() methods may not run concurrently.
"I'm not back." - Bill Harding, Twister
Originally posted by Jim Yingst:
[James]: Does that imply if s1 and s2 have different value such as:
String s1="123";
String s2="456";
The code will not be synchronized?
No. The code will be synchronized, period, because the code uses the synchronized keyword - as you see in the code. That's just terminology. But what's important here is that the code is synchronized on a particular object (or two particular objects) known as the monitor - the object whose lock is acquired for synchronization.
"I'm not back." - Bill Harding, Twister
Originally posted by Jim Yingst:
In the code you just quoted, s1 and s2 refer to two different objects, "123" and "456". However in the original code, both s1 and s2 refer to the same object, "123". That's how Java handles String literals (and String constant expressions). Two literals / constant expressions that have the same content will be made to refer to the exact same instance. There are some very subtle exceptions involving multiple classloaders, but let's skip that for now.
"I'm not back." - Bill Harding, Twister
Thanks & Regards
Kasimurugan (SCJP1.4, SCBCD1.3), Preparing SCWCD1.4
The answer of the question explains that two thread created will be synchronized and waiting each other on "synchronized" part because s1 and s2 are pointing to same string object the pool.
Is that true?
Does that imply if s1 and s2 have different value such as:
String s1="123";
String s2="456";
The code will not be synchronized?
This is wrong.The code will be synchronized in either case, (...)
all events occur in real time
Jim Yingst posted November 20, 2006 01:58 PM
quote:
The code will be synchronized in either case, (...)
This is wrong.
all events occur in real time
"I'm not back." - Bill Harding, Twister
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |