A) false, Because it does compile
B) false, as there are no runtime exceptions
When you say the class is
thread safe you want to prevent variable x from getting accessed by other threads when one of the thread is about to modify the data in x. So you need
a single [ONLY ONE] lock object across the threads to ensure this.
C) is false , making run() synchronized would make the currently executing TestSeven object as the lock object and since multiple threads are created instantiating TestSeven , this will actually have individual TestSeven objects as lock objects for each thread and this will not protect the variable x
The above code creates 100 threads and start them and here run() is synchtonized since the synchronization is applied at the method level the currently running TestSeven object will behave as lock objects so here there are 100 lock objects one each for each thread and this will not protect the variable x, The aim is to get a o/p
1,2,3,4 .... 98,99,100 and this is not achieved with the above code.
4) FALSE , The data variable is not protected, Run the program and display the value of x in doThings() and you will not see
1,2,3,4 .... 98,99,100 [ in sequence]
e) This is correct. When you make doThings() static and apply synchronized keyword, the lock object is the class object that loaded this class and now when you create 100 threads and since you have a single class the lock object would be the same class object across all 100 threads and you will see the the value of x as
1,2,3,4 .... 98,99,100 and hence data is now protected
f) this is incorrect because new Object() will be created for each of the 100 threads and you will not have a single lock object.
RULE OF THUMB : To protect data in critical section you must have a single lock object across threads. Thanks
Deepak
[ August 08, 2007: Message edited by: Burkhard Hassel ]