Self Test


The following questions will help you measure your understanding of the material presented in this chapter. If you have a rough time with some of these at first, don't beat yourself up. Some of these questions are long and intricate, expect long and intricate questions on the real exam too!

1. 

Given:

 public class Messager implements Runnable {     public static void main(String[] args) {         new Thread(new Messager("Wallace")).start() ;         new Thread(new Messager("Gromit")).start();     }     private String  name;     public Messager(String name) { this.name = name; }     public void run() {         message(1);         message(2);     }     private synchronized void message(int n) {          System.out.print(name + "-" + n + " ");     } } 

Which of the following is a possible result? (Choose all that apply.)

  1. Wallace-1 Wallace-2 Gromit-1

  2. Wallace-1 Gromit-2 Wallace-2 Gromit-1

  3. Wallace-1 Gromit-1 Gromit-2 Wallace-2

  4. Gromit-1 Gromit-2

  5. Gromit-2 Wallace-1 Gromit-1 Wallace-2

  6. The code does not compile.

  7. An error occurs at run time.

image from book

2. 

Given:

 public class Letters extends Thread {     private String name;     public Letters(String name) {         this.name = name;     }     public void write () {        System.out.print(name);        System.out.print(name);     }     public static void main(String[] args) {         new Letters("X").start();         new Letters("Y").start();     } } 

We want to guarantee that the output can be either XXYY or YYXX, but never XYXY or any other combination. Which of the following method definitions could be added to the Letters class to make this guarantee? (Choose all that apply.)

  1. public void run() { write(); }

  2. public synchronized void run() { write(); }

  3. public static synchronized void run() { write(); }

  4. public void run() { synchronized(this) { write(); } }

  5. public void run() { synchronized(Letters.class) { write(); } }

  6. public void run () { synchronized (System.out) { write (); } }

  7. public void run() { synchronized(System.out.class) { write(); } }

image from book

3. 

The following block of code creates a Thread using a Runnable target:

 Runnable target = new MyRunnable(); Thread myThread = new Thread(target); 

Which of the following classes can be used to create the target, so that the preceding code compiles correctly?

  1. public class MyRunnable extends Runnable{public void run(){}}

  2. public class MyRunnable extends Object{public void run(){}}

  3. public class MyRunnable implements Runnable{public void run(){}}

  4. public class MyRunnable implements Runnable{void run(){}}

  5. public class MyRunnable implements Runnable{public void start(){}}

image from book

4. 

Given:

  2.  class MyThread extends Thread {  3.     public static void main(String [] args) {  4.        MyThread t = new MyThread();  5.        t.start() ;  6.        System.out.print("one. ");  7.        t.start();  8.        System.out.print("two. ");  9.     } 10.     public void run() { 11.        System.out.print("Thread "}; 12.     } 13.  } 

What is the result of this code?

  1. Compilation fails.

  2. An exception occurs at runtime.

  3. Thread one. Thread two.

  4. The output cannot be determined.

image from book

5. 

Given:

  3.  class MyThread extends Thread {  4.     public static void main(String [] args) {  5.        MyThread t = new MyThread () ;  6.        Thread x = new Thread(t);  7.        x.start();  8.     }  9.     public void run() { 10.        for(int i=0;i<3;++i) { 11.           System.out.print(i + ".."); 12.        } 13.     } 14.  } 

What is the result of this code?

  1. Compilation fails.

  2. 123

  3. 0123

  4. 012

  5. An exception occurs at runtime.

image from book

6. 

Given the following

  3.  class Test {  4.     public static void main(String [] args) {  5.        printAll(args);  6.     }  7.     public static void printAll(String[] lines) {  8.        for(int i=0;i<lines.length;i++){  9.           System.out.println(lines[i]); 10.           Thread.currentThread() .sleep (1000) ; 11.        } 12.     } 13.  } 

The static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?

  1. Each String in the array lines will output, with a 1-second pause between lines.

  2. Each String in the array lines will output, with no pause in between because this method is not executed in a Thread.

  3. Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.

  4. This code will not compile.

  5. Each String in the lines array will print, with at least a one-second pause between lines.

image from book

7. 

Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)

  1. public int read(){return a+b;}

    public void set(int a, int b){this.a=a;this.b=b;}

  2. public synchronized int read(){return a+b;}

    public synchronized void set(int a, int b){this.a=a;this.b=b;}

  3. public int read(){synchronized(a){return a+b;}}

    public void get(int a, int b){synchronized(a){this.a=a;this.b=b;}}

  4. public int read(){synchronized(a){return a+b;}}

    public void set(int a, int b){synchronized(b){this.a=a;this.b=b;}}

  5. public synchronized(this) int read(){return a+b;}

    public synchronized(this) void set(int a, int b){this.a=a;this.b=b;}

  6. public int read () {synchronized (this) {return a+b;}}

    public void set(int a, int b){synchronized(this){this.a=a;this.b=b;}}

image from book

8. 

Which are methods of the Object class? (Choose all that apply.)

  1. notify();

  2. notifyAll();

  3. isInterrupted();

  4. synchronized();

  5. interrupt();

  6. wait(long msecs);

  7. sleep(long msecs);

  8. yield();

image from book

9. 

Given the following

  1.  public class WaitTest {  2.     public static void main(String [] args) {  3.        System.out.print("1 ") ;  4.        synchronized(args) {  5.           System.out.print("2 " ) ;  6.           try {  7.              args.wait();  8.           }  9.           catch(InterruptedException e){} 10.        } 11.        System.out.print("3 "); 12.     } 13.  } 

What is the result of trying to compile and run this program?

  1. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7.

  2. 1 2 3

  3. 1 3

  4. 1 2

  5. At runtime, it throws an IllegalMonitorStateException when trying to wait.

  6. It will fail to compile because it has to be synchronized on the this object.

image from book

10. 

Assume the following method is properly synchronized and called from a thread A on an object B:

 wait(2000); 

After calling this method, when will the thread A become a candidate to get another turn at the CPU?

  1. After object B is notified, or after two seconds.

  2. After the lock on B is released, or after two seconds.

  3. Two seconds after object B is notified.

  4. Two seconds after lock B is released.

image from book

11. 

Which are true? (Choose all that apply.)

  1. The notifyAll() method must be called from a synchronized context.

  2. To call wait(), an object must own the lock on the thread.

  3. The notify() method is defined in class java.lang.Thread.

  4. When a thread is waiting as a result of wait(), it release its lock.

  5. The notify() method causes a thread to immediately release its lock.

  6. The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they're waiting on.

image from book

12. 

Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:

 public class Logger {     private StringBuilder contents = new StringBuilder();     public void log(String message) {         contents.append(System.currentTimeMillis());         content a.append(": ");         contents.append(Thread.currentThread().getName());         contents.append(message);         contents.append("\n");     }     public String getContents() { return contents.toString(); } } 

How can we ensure that instances of this class can be safely used by multiple threads?

  1. This class is already thread-safe.

  2. Replacing stringBuilder with StringBuffer will make this class thread-safe.

  3. Synchronize the log() method only.

  4. Synchronize the getcontents() method only.

  5. Synchronize both log() and getContents().

  6. This class cannot be made thread-safe.

image from book

13. 

Given:

 public static synchronized void main(String[] args) throws  InterruptedException {     Thread t = new Thread();     t.start () ;     System.out.print ("X") ;     t.wait (10000) ;     System.out.print("Y"); } 

What is the result of this code?

  1. It prints X and exits.

  2. It prints X and never exits.

  3. It prints XY and exits almost immeditately.

  4. It prints XY with a 10-second delay between X and Y.

  5. It prints XY with a 10000-second delay between X and Y.

  6. The code does not compile.

  7. An exception is thrown at runtime.

image from book

14. 

Given the following,

 class MyThread extends Thread {    MyThread() {      System.out.print(" MyThread");    }    public void run() {      System.out.print(" bar");    }    public void run(String s) {       System.out.print(" baz");    } } public class TestThreads {    public static void main (String [] args) {      Thread t = new MyThread() {        public void run() {          System.out.print(" foo");        }      };      t.start () ; } } 

What is the result?

  1. foo

  2. MyThread foo

  3. MyThread bar

  4. foo bar

  5. foo bar baz

  6. bar foo

  7. Compilation fails.

  8. An exception is thrown at runtime.

image from book

15. 

Given

 public class ThreadDemo {     synchronized void a() { actBusy(); }     static synchronized void b() { actBusy(); }     static void actBusy() {         try {             Thread.sleep(1000);         catch (InterruptedException e) {}     }     public static void main(String[] args) {         final ThreadDemo x = new ThreadDemo();         final ThreadDemo y = new ThreadDemo();         Runnable runnable = new Runnable(){             public void run() {                 int option = (int) (Math.random(} * 4);                 switch (option) {                     case 0: x.a(); break;                     case 1: x.b(); break;                     case 2: y.a(); break;                     case 3: y.b(); break;                 }             }         };         Thread threadl = new Thread(runnable);         Thread thread2 = new Thread(runnable);         thread1.start();         thread2.start();     } } 

Which of the following pairs of method invocations could NEVER be executing at the same time? (Choose all that apply.)

  1. x.a() in thread1, and x.a() in thread2

  2. x.a() in thread1, and x.b() in thread2

  3. x.a() in thread1, and y.a() in thread2

  4. x.a() in thread1, and y.b() in thread2

  5. x.b() in thread1, and x.a() in thread2

  6. x.b() in thread1, and x.b() in thread2

  7. x.b() in thread1, and y.a() in thread2

  8. x.b() in thread1, and y.b() in thread2

image from book

16. 

Given the following,

  1. public class Test {  2.  public static void main (String [] args) {  3.    final Foo f = new Foo();  4.   Thread t = new Thread(new Runnable() {  5.         public void run() {  6.        f.doStuff () ;  7.       }  8.   });  9.   Thread g = new Thread() { 10.    public void run() { 11.         f.doStuff(); 12.      } 13.     }; 14.     t.start(); 15.     g.start(); 16.  } 17. }  1. class Foo {  2.   int x = 5;  3.  public void doStuff ()  4.     if (x < 10) {  5.       // nothing to do  6.      try {  7.         wait();  8.      } catch(InterruptedException ex) { }  9.     } else { 10.      System.out.println("x is " + x++); 11.      if (x >= 10) { 12.          notify() ; 13.        } 14.     } 15.  } 16. } 

What is the result?

  1. The code will not compile because of an error on line 12 of class Foo.

  2. The code will not compile because of an error on line 7 of class Foo.

  3. The code will not compile because of an error on line 4 of class Test.

  4. The code will not compile because of some other error in class Test.

  5. An exception occurs at runtime.

  6. x is 5

    x is 6

image from book

17. 

Given:

 public class TwoThreads {     static Thread laurel, hardy;     public static void main(String[] args) {         laurel = new Thread() {             public void run() {                 System.out.println("A");                 try {                     hardy.sleep (1000);                 } catch (Exception e) {                     System.out.println("B");                 }                 System.out.println("C");             }         };         hardy = new Thread(} {             public void run() {                 System.out.println("D");                 try {                     laurel.wait();                 } catch (Exception e) {                     System.out.println("E");                 }                 System.out.println("F");             }         };         laurel.start();         hardy.start();     } } 

Which letters will eventually appear somewhere in the output? (Choose all that apply.)

  1. A

  2. B

  3. C

  4. D

  5. E

  6. F

  7. The answer cannot be reliably determined.

  8. The code does not compile.

image from book

Answers

1. 

þ  

C is correct. Both threads will print two messages each.wallace-1 must be before Wallace-2, and Gromit-1 must be before Gromit-2. Other than that, the Wallace and Gromit messages can be intermingled in any order.

ý  

A, B, D, E, F, and G are incorrect based on the above. (Objective 4.1)

2. 

þ  

E and F are correct. E and F both cause both threads to lock on the same object, which will prevent the threads from running simultaneously, and guarantee XXYY or YYXX. It's a bit unusual to lock on an object like system.out, but it's perfectly legal, and both threads are locking on the same object.

ý  

A can't guarantee anything since it has no synchronization. B and D both synchronize on an instance of the Letters class—but since there are two different instances in the main() method, the two threads do not block each other and may run simultaneously, resulting in output like xyxy. C won't compile because it tries to override run() with a static meth-od, and also calls a non-static method from a static method. G won't compile because System.out.class is nonsense. A class literal must start with a class name. System.out is a field not a class, so System.out.class is not a valid class literal. (Objective 4.3)

3. 

þ  

C is correct. The class implements the Runnable interface with a legal run() method.

ý  

A is incorrect because interfaces are implemented, not extended. B is incorrect because even though the class has a valid public void run( ) method, it does not implement the Runnable interface. D is incorrect because the run() method must be public. E is incorrect because the method to implement is run(), not start(). (Objective 4.1)

4. 

þ  

B is correct. When the start( ) method is attempted a second time on a single Thread object, the method will throw an IllegalThreadStateException. (Although this behavior is specified in the API, some JVMs don't consistently throw an exception in this case). Even if the thread has finished running, it is still illegal to call start() again.

ý  

A is incorrect because compilation will succeed. For the most part, the Java compiler only checks for illegal syntax, rather than class-specific logic. C and D are incorrect because of the logic explained above. (Objective 4.1)

5. 

þ  

D is correct. The thread MyThread will start and loop three times (from 0 to 2).

ý  

A is incorrect because the Thread class implements the Runnable interface; therefore, in line 5, Thread can take an object of type Thread as an argument in the constructor (this is NOT recommended). B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2. E is incorrect based on the above. (Obj. 4.1)

6. 

þ  

D is correct. The sleep ( ) method must be enclosed in'a try/catch block, or the method printAll () must declare it throws the interruptedException.

ý  

E is incorrect, but it would be correct if the InterruptedException was dealt with (A is too precise). B is incorrect (even if the InterruptedException was dealt with) because all Java code, including the main() method, runs in threads. C is incorrect. The sleep() method is static, it always affects the currently executing thread. (Objective 4.2)

7. 

þ  

B and F are correct. By marking the methods as synchronized, the threads will get the lock of the this object before proceeding. Only one thread will be setting or reading at any given moment, thereby assuring that read() always returns the addition of a valid pair.

ý  

A is incorrect because it is not synchronized; therefore, there is no guarantee that the values added by the read() method belong to the same pair. C and D are incorrect; only objects can be used to synchronize on. E fails—it is not possible to select other objects (even this) to synchronize on when declaring a method as synchronized. (Obj. 4.3)

8. 

þ  

A, B, and F are correct. They are all related to the list of threads waiting on the specified object.

ý  

C, E, G, and H are incorrect answers. The methods isinterrupted() and interrupt() are instance methods of Thread. The methods sleep() and yield () are static methods of Thread. D is incorrect because synchronized is a keyword and the synchronized() construct is part of the Java language. (Objective 4.2)

9. 

þ  

D is correct. l and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. It's frozen at line 7.

ý  

A is incorrect; IllegalmonitorstateException is an unchecked exception. B and C are incorrect; 3 wilt never be printed, since this program will wait forever. E is incorrect because IllegalMonitorstateException will never be thrown because the wait() is done on args within a block of code synchronized on args. F is incorrect because any object can be used to synchronize on and this and static don't mix. (Objective 4.4)

10. 

þ  

A is correct. Either of the two events will make the thread a candidate for running again.

ý  

B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. C is incorrect because the thread will become a candidate immediately after notification. D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released. (Objective 4.4)

11. 

þ  

A is correct because notifyAll() (and wait () and notify()) must be called from within a synchronized context. D is a correct statement.

ý  

B is incorrect because to call wait(), the thread must own the lock on the object that wait() is being invoked on, not the other way around. C is wrong because notify() is defined in java.lang.object. E is wrong because notify() will not cause a thread to release its locks. The thread can only release its locks by exiting the synchronized code. F is wrong because notifyAll() notifies all the threads waiting on a particular locked object, not all threads waiting on any object. (Objective 4.4)

12. 

þ  

E is correct. Synchronizing the public methods is sufficient to make this safe, so F is false. This class is not thread-safe unless some sort of synchronization protects the changing data.

ý  

B is not correct because although a StringBuffar is synchonized internally, we callappend() multiple times, and nothing would prevent two simultaneous log() calls from mixing up their messages. C and D are not correct because if one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse. (You don't want to call getstring() on the StringBuffer as it's resizing its internal character array.) (Objective 4.3)

13. 

þ  

G is correct. The code does not acquire a lock on t before calling t.wait(), so it throws an IllegalThreadStateException. The method is synchronized, but it's not synchronized on t so the exception will be thrown. If the wait were placed inside a synchronized(t) block, then the answer would have been D.

ý  

A, B, C, D, E, and F are incorrect based the logic described above. (Objective 4.2)

14. 

þ  

B is correct. The first line of main we're constructing an instance of an anonymous inner class extending from MyThread. So the MyThread constructor runs and prints MyThread. Next, main() invokes Start() on the new thread instance, which causes the overridden run() method (the run() method in the anonymous inner class) to be invoked.

ý  

A, C, D, E, F, G and H are incorrect based on the logic described above. (Objective 4.l)

15. 

þ  

A, F, and H. A is a right answer because when synchronized instance methods are called on the same instance, they block each other. F and H can't happen because synchronized static methods in the same class block each other, regardless of which instance was used to call the methods. (An instance is not required to call static methods; only the class.)

ý  

C could happen because synchronized instance methods called on different instances do not block each other. B, D, E, and G could all happen because instance methods and static methods lock on different objects, and do not block each other. (Objective 4.3) .

16. 

þ  

E is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception.

ý  

A, B, C, and D are incorrect because the code compiles without errors. F is incorrect because the exception is thrown before there is any output. (Objective 4.4)

17. 

þ  

A, C, D, E, and F are correct. This may look like laurel and hardy are battling to cause the other to sleep() or wait()—but that's not the case. Since sleep() is a static method, it affects the current thread, which is laurel (even though the method is invoked using a reference to hardy). That's misleading but perfectly legal, and the Thread laurel is able to sleep with no exception, printing A and c (after a 1-second delay). Meanwhile hardy tries to call laurel.wait()—but hardy has not synchronized on laurel, so calling laurel.wait() immediately causes an IllegalThreadStateException, and so hardy prints D, E, and F. Although the order of the output is somewhat indeterminate (we have no way of knowing whether A is printed before D, for example) it is guaranteed that A, C, D, E, and F will all be printed in some order, eventually—so G is incorrect.

ý  

B, G, and H are incorrect based on the above. (Objective 4.4)




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net