This question is from Sun practice exams. I need to understand how to approach such a question:
Which is true?
A The output can never contain the value 10.
B The output can never contain the value 30.
C The output can never contain the value 297.
D The output can never contain the value 1020.
E The output can never contain the value 1130.
You have 100 threads with the same target, and each thread can increment i at most 11 times. Then, 1130 seems impossible. The rest of the items I think are plausible, as there is very little guaranteed.
The way I approach this: Look at what each thread does. Is the method that changes state synchronized, or not? Cross out the statement with the yield() invocation (as that is not guaranteed to do anything.) And remember that very little is guaranteed when multiple threads access the same object without synchronization.
Ruben Soto wrote:You have 100 threads with the same target, and each thread can increment i at most 11 times. Then, 1130 seems impossible. The rest of the items I think are plausible, as there is very little guaranteed.
The way I approach this: Look at what each thread does. Is the method that changes state synchronized, or not? Cross out the statement with the yield() invocation (as that is not guaranteed to do anything.) And remember that very little is guaranteed when multiple threads access the same object without synchronization.
can you explain how did you come to this conclusion [ marked in bold] ??
Ruben Soto wrote:You have 100 threads with the same target, and each thread can increment i at most 11 times. Then, 1130 seems impossible. The rest of the items I think are plausible, as there is very little guaranteed.
The way I approach this: Look at what each thread does. Is the method that changes state synchronized, or not? Cross out the statement with the yield() invocation (as that is not guaranteed to do anything.) And remember that very little is guaranteed when multiple threads access the same object without synchronization.
can you explain how did you come to this conclusion [ marked in bold] ??
Piya,
Look at the code:
Each thread can increment i once at line 8, and 10 times in the for loop. Total is 11 times per thread. Since we have 100 threads, that makes a total number of possible increments of 1100.
Vyas Sanzgiri wrote:I see how you get to the answer and I know that answer is correct.
But line 8 will not execute every time.
Vyas,
I know it won't execute everytime. But that will only make the total number less than 1100, and we are just wanting to prove that 1130 is impossible. You have to know when you can simply approximate a number and bound it. What I did is provide an upper bound for the number of increments (although that upper bound can't be practically attained.) As long as the upper bound is less than 1130, you can be sure that the actual value of i will always be less than 1130.