J2EEOnline J2EE  





Java Questions 1 - 10   «Prev  Next»

Java Questions 9

  1. Can a class have both synchronized and non-synchronized methods?
    Answer:
    Yes
  2. When you syncrhonize a method, which object must be acquired?
    Answer:
    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)?
    Answer:
    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?
    Answer:
    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?
    Answer:
    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?
    Answer:
    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?
    Answer:
    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?
    Answer:
    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?
    Answer:
    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.
    Answer:
    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.