J2EEOnline J2EE  

Java Questions 1 - 10   «Prev  Next»

Java Thread Synchronization Questions

Java Questions 10

  1. Will a static synchronized method and a non-static synchronized method ever block each other?
    No. The static method locks on a Class instance while the non-static method locks on the this instance.
  2. Does the wait() method give up a lock?
  3. When do you need to synchronize to protect data?
    Anytime more than one thread is accessing mutable data. This is to make sure that 2 threads are not changing the mutable data at the same time.
  4. What is the purpose of synchronization?
    Threads working with or operating on the same data need to operate on the data one at a time.
  5. How would you access changeable data in a static field?
    You would use a static method to access it.
  6. What happens when you have a static method access a non-static field and you synchronize the method?
    You acquire a lock on the Class Object.

  7. Why can a static synchronized method and a non-static synchronized method run at the same time?
    Because they will not block each other.
  8. What must you do in order to keep a class thread safe?
    Methods that access changeable fields must be synchronized.
  9. What generalization can you make regarding static fields and methods?
    Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non-static synchronized methods.
  10. li> How would you describe a class that is thread safe?
    When a class has been synchronized to protect its data, we say that the class is thread-safe