CS 1520 Summer 2009 Quiz 1

SOLUTIONS

Thursday, June 4, 2009

 

1)    Fill in the Blanks and T/F (18 points – 2 points each.  For fill in the blanks provide the MOST appropriate answer.  For T/F CORRECT false statements)

a)     Syntactically, threading in Java can be done in two basic ways:  ____having a class extend the Thread class _______ and _____having a class implement the Runnable interface_______

b)    A Java Thread whose run() method has completed can run it again through a call to the restart() method _______F_____ (T or F)  Java Threads cannot be restarted once they stop

c)     Given an object with 2 synchronized methods, at most 2 Threads can be executing these methods "at the same time" – one Thread for each method. _____F_____ (T or F) Only 1 thread may be executing any of the synchronized methods at one time.

d)    The stop() method in Java's Thread class is deprecated because ______It can lead to data corruption if a thread is in a critical area when it is stopped________________

e)     In addition to the wait() / notify() mechanism, Java (since 1.5) allows a more general signaling mechanism via the ___Lock_________________ and _____Condition_________ interfaces.

f)     Logically, Sockets in Java use a _____connection-oriented______________ protocol, similar in nature to using a telephone for voice conversations.

g)     The _____accept()_____________ method of a Java ServerSocket is blocking, waiting until a client connects, and then returning the resulting  ______Socket________________.

h)    Given a set of N clients who must interact with only the server (and not each other), the overall time to process the clients will be less if they are accessed "in parallel" using threading rather than if they are processed sequentially.  _____F______ (T or F)                      Due to context switching the overall time will likely be higher if the clients are processed "in parallel".

i)      If an Applet that was legitimately signed using a valid key is subsequently altered and not signed again, the JRE will prevent the Applet from executing. ____T_____ (T or F)  


2)    Short Answers (12 points – 6 + 6)

a)     Consider the idea of cooperation synchronization and specifically the Consumer / Producer problem.  Assume that a Producer is calling a synchronized "insert" method to add an item to the buffer, but that the buffer is currently full.  One way to handle this issue is for the Producer to simply exit the "insert" method and try again, until it is able to add the item.  Explain if this approach is a good one and why (or why not).  Be specific and detailed.

 

The described approach is poor because no mechanism is used to determine when the buffer might again have free space.  Thus, the Producer may spin repeatedly, each time calling "insert" and each time finding the buffer full.  This is very wasteful of CPU cycles.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

b)    Assume a programmer is implementing a client program (which will connect to a server using a Socket) in Java using an Applet.  What are some limitations with this approach and why do these limitations exist?  How can the programmer get around these limitations?  Be specific.

 

In the case described above, the Applet will not by default be able to access a remote server, nor will it be able to access any files on the client machine.  A SecurityManager in the JRE will prevent this access.  This is a security measure to protect clients from possibly malicious applets.  To get around this security measure, the author can digitally sign the Applet and the client can accept the author's certificate.  This allows the Applet to bypass the security "sandbox" and to access the filesystem and network.


3)     Tracing (10 points – 5 points each) Consider the Java program below, then answer the questions on the following page.

< ORIGINAL CODE REMOVED >

 

a)     All of the words will appear in the output.   For a given id, the words will appear in the order shown in the String array.  However, the words for the various ids may be interleaved, as we cannot predict that all words for a given MyClass object will be written without interruption.

 

b)    Since the "out" method is now synchronized, we know that all of the words for a given MyClass will be output together – without interruption.  However, we still cannot predict the order that the threads will execute, since they are all contending for the CPU  /  Lock without sleeping.

 

 

 


4)    Coding (10 points) Consider the Java server program shown below that sorts lists of words sent to it by clients and sends the resulting sorted words back to the clients.  Write a client program that, when connecting to the server produces the output shown below.  Note that the client program uses the command line for input, and be sure to coordinate the I/O of the client with that of the server.

import java.util.*;

import java.io.*;

import java.net.*;

 

public class Server

{

      public static final int PORT = 8800;

      public static void main(String [] args) throws IOException

      {

            ServerSocket s = new ServerSocket(PORT);

            System.out.println("Server running. Hit CTRL-C to stop");

            while (true)

            {

                  try

                  {

                        Socket socket = s.accept();

                        System.out.println("Client accepted");

                        PrintWriter output =

                              new PrintWriter(

                              new BufferedWriter(

                              new OutputStreamWriter(

                              socket.getOutputStream())), true);

 

                        BufferedReader input =

                              new BufferedReader(

                              new InputStreamReader(

                              socket.getInputStream()));        

 

                        ArrayList<String> data = new ArrayList<String>();

                        String curr = input.readLine();

                        while (!curr.equals("!DONE!"))

                        {

                              data.add(curr);

                              curr = input.readLine();

                        }

                        Collections.sort(data);

                        for (int i = 0; i < data.size(); i++)

                        {

                              output.println(data.get(i));

                        }

                  }

                  catch (Exception e)

                  {

                        System.out.println("Problem");

                  }

            }

      }

}

C:\>java Client localhost this is a test

a is test this

 

C:\>java Client localhost will this sort the words

sort the this will words

 


 

// ONE POSSIBLE SOLUTION

import java.net.*;

import java.io.*;

 

  public class Client

  {

        static final int port = 8800;

 

        public static void main( String [] args)

        {

              try

              {

                    if (args.length < 2)

                       System.out.println("Not enough arguments...quitting");

                    else

                    {

                          String host = args[0];

                          InetAddress addr = InetAddress.getByName(host);

                          Socket socket = new Socket(addr, port);

           

                          PrintWriter output =

                                new PrintWriter(

                                new BufferedWriter(

                                new OutputStreamWriter(

                                socket.getOutputStream())), true);        

                          BufferedReader input =

                                new BufferedReader(

                                new InputStreamReader(

                                socket.getInputStream()));

                          for (int i = 1; i < args.length; i++)

                          {

                                output.println(args[i]);

                          }

                          output.println("!DONE!");

                          for (int i = 1; i < args.length; i++)

                          {

                                System.out.print(input.readLine() + " ");

                          }

                          System.out.println();

                    }

              }     

              catch( Exception e)

              {

                    System.out.println("Problem with connection");

              }

        }

  }