- Can we rely on the sleep method to really switch threads?
- And how can we be sure that the JVM won't start thread mt2 right away before executing "sbl.append("AAA");"?
Felipe HSilva wrote:Hi all,
Thanks for all the replies. I believe we have a consensus that if we need to find an answer for all cases, the "unpredictable result" would be more adequate. So the question that remains is what should be the correct answer if I see this on the real exam? Well, if "unpredictable result" was one of the answers I would go for it. I just hope this is the way the exam's creators think.
Ruben Soto wrote:
Technically there are two possibilities:
- If the evaluation of the x in mt1's switch gets to run before the assignment x = 2 in the main thread, and mt1 acquires the lock on sbf before the sbf.append("AAA") call in the main thread, then the output will be "Builder passed" and the program will never finish normally.
- In all other cases, the output will be "Builder passed" "Buffer passed" and the program will finish normally.
The second scenario is not very likely, due to the Thread.sleep(1000) statement before the assignment x = 2. But it is theoretically possible. If you see this kind of question in the exam you should probably take a guess using your common sense. Hopefully you won't see this kind of question in the exam though.
Felipe HSilva wrote:Well, if "unpredictable result" was one of the answers I would go for it. I just hope this is the way the exam's creators think.