J2EEOnline J2EE  

Java Questions 1 - 10   «Prev  Next»

Java Questions 9

  1. Can a class have both synchronized and non-synchronized methods?
  2. When you syncrhonize a method, which object must be acquired?
    When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired.
  3. Whose lock is used to protect the static methods of the class (if they are synchronized)?
    It is the java.lang.Class instance whose lock is used to protect the static method of the class (if they are synchronized) .
  4. What does the synchronized keyword enable you to achieve with threads?
    The Java programming language provides two basic synchronization idioms: 1) synchronized methods and 2) synchronized blocks.
    The keyword synchronized designates methods and blocks of code for safe, serialized access within an object.
  5. What is the function of a .class appended at the end of a Java class?
    That is called a class literal. It is a special feature in the Java language that tells the compiler (which tells the JVM) go and find me the instance of Class that represents the class called MyClass.

  6. What is the purpose of getting the lock on an object?
    So that other threads cannot modify the object while the block of code is executing.
  7. What is the difference between a StringBuffer and String object?
    Strings cannot be modified once they are created and they are immutable.
    The String class is final.
  8. What do you call the condition when a thread tries to enter a synchronized method and the lock is already taken?
    The thread is said to block on the object's lock.
  9. If a lock is released, does this mean that a thread will get the object?
    No. Just because a lock is released does not mean that any particular thread will obtain the object.
  10. What is the difference between
    1. Threads calling non-static synchronized methods in the same class
    2. Threads calling static synchronized methods in the same class?
    This is has to do with the definition of static.
    For a) they will only block each other if they are invoked using the same instance.
    For b), these threads will always block each other.