archive-edu.com » EDU » H » HWS.EDU

Total: 727

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Javanotes 7.0, Section 10.4 -- Programming with the Java Collection Framework
    the page number and add it to the index with the term as the key TreeSet Integer firstRef new TreeSet Integer firstRef add pageNum pageNum is autoboxed to give an Integer index put term firstRef else references is the set of page references that we have found previously for the term Add the new page number to that set This set is already associated to term in the index references add pageNum pageNum is autoboxed to give an Integer The only other thing we need to do with the index is print it out We want to iterate through the index and print out each term together with the set of page references for that term We could use an Iterator to iterate through the index but it s much easier to do it with a for each loop The loop will iterate through the entry set of the map see Subsection 10 3 2 Each entry is a key value pair from the map the key is a term and the value is the associated set of page references Inside the for each loop we will have to print out a set of Integers which can also be done with a for each loop So here we have an example of nested for each loops You might try to do the same thing entirely with iterators doing so should give you some appreciation for the for each loop Here is a subroutine that will print the index Print each entry in the index void printIndex for Map Entry String TreeSet Integer entry index entrySet String term entry getKey TreeSet Integer pageSet entry getValue System out print term for int page pageSet System out print page System out println The hardest thing here is the name of the type Map Entry String TreeSet Integer Remember that the entries in a map of type Map K V have type Map Entry K V so the type parameters in Map Entry String TreeSet Integer are simply copied from the declaration of index Another thing to note is that I used a loop control variable page of type int to iterate through the elements of pageSet which is of type TreeSet Integer You might have expected page to be of type Integer not int and in fact Integer would have worked just as well here However int does work because of automatic type conversion It s legal to assign a value of type Integer to a variable of type int To be honest I was sort of surprised that this worked when I first tried it This is not a lot of code considering the complexity of the operations I have not written a complete indexing program but Exercise 10 5 presents a problem that is almost identical to the indexing problem By the way in this example I would prefer to print each list of page references with the integers separated by commas In the printIndex method given above they are separated by spaces There is an extra space after the last page reference in the list but it does no harm since it s invisible in the printout An extra comma at the end of the list would be annoying The lists should be in a form such as 17 42 105 and not 17 42 105 The problem is how to leave that last comma out Unfortunately this is not so easy to do with a for each loop It might be fun to look at a few ways to solve this problem One alternative is to use an iterator Iterator Integer iter pageSet iterator int firstPage iter next In this program we know the set has at least one element System out print firstPage while iter hasNext int nextPage iter next System out print nextPage Another possibility is to use the fact that the TreeSet class defines a method first that returns the first item in the set that is the one that is smallest in terms of the ordering that is used to compare items in the set It also defines the method last We can solve our problem using this method and a for each loop int firstPage pageSet first Find out the first page number in the set for int page pageSet if page firstPage System out print Output comma only if this is not the first page System out print page Finally here is an elegant solution using a subset view of the tree See Subsection 10 3 2 Actually this solution might be a bit extreme int firstPage pageSet first Get first item which we know exists System out print firstPage Print first item with no comma for int page pageSet tailSet firstPage 1 Process remaining items System out print page 10 4 3 Using a Comparator There is a potential problem with our solution to the indexing problem If the terms in the index can contain both upper case and lower case letters then the terms will not be in alphabetical order The ordering on String is not alphabetical It is based on the Unicode codes of the characters in the string The codes for all the upper case letters are less than the codes for the lower case letters So for example terms beginning with Z come before terms beginning with a If the terms are restricted to use lower case letters only or upper case only then the ordering would be alphabetical But suppose that we allow both upper and lower case and that we insist on alphabetical order In that case our index can t use the usual ordering for Strings Fortunately it s possible to specify a different method to be used for comparing the keys of a map This is a typical use for a Comparator Recall that an object that implements the interface Comparator T defines a method for comparing two objects of type T public int compare T obj1 T obj2 This method should return an

    Original URL path: http://math.hws.edu/javanotes/c10/s4.html (2016-02-07)
    Open archived version from archive


  • Javanotes 7.0, Section 11.2 -- Files
    ends which eliminates the need to close it by hand in a finally clause This assumes that you will open the resource and use it in the same try catch As an example the sample program ReverseFileWithResources java is another version of the example we have been looking at In this case try catch statements using the resource pattern are used to read the data from a file and to write the data to a file My original program opened a file in one try statement and used it in another try statement The resource pattern requires that it all be done in one try which requires some reorganization of the code and can sometimes make it harder to determine the exact cause of an exception Here is the try catch statement from the sample program that opens the input file reads from it and closes it automatically try TextReader data new TextReader new FileReader data dat Read numbers adding them to the ArrayList while data eof false Read until end of file double inputNumber data getlnDouble numbers add inputNumber catch FileNotFoundException e Can only be caused by the TextReader constructor System out println Can t open input file data dat System out println Error e return Return from main since an error has occurred Otherwise the program would try to do the output catch IOException e Can occur when the TextReader tries to read a number System out println Error while reading from file e return Return from main since an error has occurred The resource data is constructed on the first line The syntax requires a declaration of the resource with an initial value in parentheses after the word try It s possible to have several resource declarations separated by semicolons They will be closed in the order opposite to the order in which they are declared 11 2 2 Files and Directories The subject of file names is actually more complicated than I ve let on so far To fully specify a file you have to give both the name of the file and the name of the directory where that file is located A simple file name like data dat or result dat is taken to refer to a file in a directory that is called the current directory also known as the default directory or working directory The current directory is not a permanent thing It can be changed by the user or by a program Files not in the current directory must be referred to by a path name which includes both the name of the file and information about the directory where it can be found To complicate matters even further there are two types of path names absolute path names and relative path names An absolute path name uniquely identifies one file among all the files available to the computer It contains full information about which directory the file is in and what the file s name is A relative path name tells the computer how to locate the file starting from the current directory Unfortunately the syntax for file names and path names varies somewhat from one type of computer to another Here are some examples data dat on any computer this would be a file named data dat in the current directory home eck java examples data dat This is an absolute path name in a UNIX operating system including Linux and Mac OS X It refers to a file named data dat in a directory named examples which is in turn in a directory named java C eck java examples data dat An absolute path name on a Windows computer examples data dat a relative path name under UNIX examples is the name of a directory that is contained within the current directory and data dat is a file in that directory The corresponding relative path name for Windows would be examples data dat examples data dat a relative path name in UNIX that means go to the directory that contains the current directory then go into a directory named examples inside that directory and look there for a file named data data In general means go up one directory The corresponding path on Windows is examples data dat When working on the command line it s safe to say that if you stick to using simple file names only and if the files are stored in the same directory with the program that will use them then you will be OK Later in this section we ll look at a convenient way of letting the user specify a file in a GUI program which allows you to avoid the issue of path names altogether It is possible for a Java program to find out the absolute path names for two important directories the current directory and the user s home directory You can then use the path name for example in a constructor for a File or a PrintWriter The names of these directories are system properties and they can be read using the function calls System getProperty user dir returns the absolute path name of the current directory as a String System getProperty user home returns the absolute path name of the user s home directory as a String To avoid some of the problems caused by differences in path names between platforms Java has the class java io File An object belonging to this class represents a file More precisely an object of type File represents a file name rather than a file as such The file to which the name refers might or might not exist Directories are treated in the same way as files so a File object can represent a directory just as easily as it can represent a file A File object has a constructor new File String that creates a File object from a path name The name can be a simple name a relative path or an absolute path For

    Original URL path: http://math.hws.edu/javanotes/c11/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 11.3 -- Programming With Files
    store the data in a file or for some applications in a database but the data in a database is itself stored in files Consider a phone book program that allows the user to keep track of a list of names and associated phone numbers The program would make no sense at all if the user had to create the whole list from scratch each time the program is run It would make more sense to think of the phone book as a persistent collection of data and to think of the program as an interface to that collection of data The program would allow the user to look up names in the phone book and to add new entries Any changes that are made should be preserved after the program ends The sample program PhoneDirectoryFileDemo java is a very simple implementation of this idea It is meant only as an example of file use the phone book that it implements is a toy version that is not meant to be taken seriously This program stores the phone book data in a file named phone book demo in the user s home directory To find the user s home directory it uses the System getProperty method that was mentioned in Subsection 11 2 2 When the program starts it checks whether the file already exists If it does it should contain the user s phone book which was saved in a previous run of the program so the data from the file is read and entered into a TreeMap named phoneBook that represents the phone book while the program is running See Subsection 10 3 1 In order to store the phone book in a file some decision must be made about how the data in the phone book will be represented For this example I chose a simple representation in which each line of the file contains one entry consisting of a name and the associated phone number A percent sign separates the name from the number The following code at the beginning of the program will read the phone book data file if it exists and has the correct format File userHomeDirectory new File System getProperty user home File dataFile new File userHomeDirectory phone book data A file named phone book data in the user s home directory if dataFile exists System out println No phone book data file found A new one System out println will be created if you add any entries System out println File name dataFile getAbsolutePath else System out println Reading phone book data try Scanner scanner new Scanner dataFile while scanner hasNextLine Read one line from the file containing one name number pair String phoneEntry scanner nextLine int separatorPosition phoneEntry indexOf if separatorPosition 1 throw new IOException File is not a phonebook data file name phoneEntry substring 0 separatorPosition number phoneEntry substring separatorPosition 1 phoneBook put name number catch IOException e System out println Error in phone book data file System out println File name dataFile getAbsolutePath System out println This program cannot continue System exit 1 The program then lets the user do various things with the phone book including making modifications Any changes that are made are made only to the TreeMap that holds the data When the program ends the phone book data is written to the file if any changes have been made while the program was running using the following code if changed System out println Saving phone directory changes to file dataFile getAbsolutePath PrintWriter out try out new PrintWriter new FileWriter dataFile catch IOException e System out println ERROR Can t open data file for output return for Map Entry String String entry phoneBook entrySet out println entry getKey entry getValue out flush out close if out checkError System out println ERROR Some error occurred while writing data file else System out println Done The net effect of this is that all the data including the changes will be there the next time the program is run I ve shown you all the file handling code from the program If you would like to see the rest of the program see the source code file PhoneDirectoryFileDemo java 11 3 3 Files in GUI Programs The previous examples in this section use a command line interface but graphical user interface programs can also manipulate files Programs typically have an Open command that reads the data from a file and displays it in a window and a Save command that writes the data from the window into a file We can illustrate this in Java with a simple text editor program TrivialEdit java The window for this program uses a JTextArea component to display some text that the user can edit It also has a menu bar with a File menu that includes Open and Save commands These commands are implemented using the techniques for reading and writing files that were covered in Section 11 2 When the user selects the Open command from the File menu in the TrivialEdit program the program pops up a file dialog box where the user specifies the file It is assumed that the file is a text file A limit of 10000 characters is put on the size of the file since a JTextArea is not meant for editing large amounts of text The program reads the text contained in the specified file and sets that text to be the content of the JTextArea The program also sets the title bar of the window to show the name of the file that was opened All this is done in the following method which is just a variation of the readFile method presented in Section 11 2 Carry out the Open command by letting the user specify a file to be opened and reading up to 10000 characters from that file If the file is read successfully and is not too long then the text from the file replaces the text in the JTextArea public void doOpen if fileDialog null fileDialog new JFileChooser fileDialog setDialogTitle Select File to be Opened fileDialog setSelectedFile null No file is initially selected int option fileDialog showOpenDialog this if option JFileChooser APPROVE OPTION return User canceled or clicked the dialog s close box File selectedFile fileDialog getSelectedFile Scanner in try in new Scanner selectedFile catch FileNotFoundException e JOptionPane showMessageDialog this Sorry but an error occurred while trying to open the file n e return try StringBuilder input new StringBuilder while in hasNextLine String lineFromFile in nextLine if lineFromFile null break End of file has been reached input append lineFromFile input append n if input length 10000 throw new IOException Input file is too large for this program text setText input toString editFile selectedFile setTitle TrivialEdit editFile getName catch Exception e JOptionPane showMessageDialog this Sorry but an error occurred while trying to read the data n e finally in close In this program the instance variable editFile is used to keep track of the file that is currently being edited if any and the setTitle method from class JFrame is used to set the title of the window to show the name of the file TrivialEdit is defined as a subclass of JFrame Similarly the response to the Save command is a minor variation on the writeFile method from Section 11 2 I will not repeat it here If you would like to see the entire program you will find the source code in the file TrivialEdit java 11 3 4 Storing Objects in Files Whenever data is stored in files some definite format must be adopted for representing the data As long as the output routine that writes the data and the input routine that reads the data use the same format the files will be usable However as usual correctness is not the end of the story The representation that is used for data in files should also be robust See Section 8 1 To see what this means we will look at several different ways of representing the same data This example builds on the example SimplePaint2 java from Subsection 7 3 3 You might want to run it now to remind yourself of what it can do In that program the user could use the mouse to draw simple sketches Now we will add file input output capabilities to that program This will allow the user to save a sketch to a file and later read the sketch back from the file into the program so that the user can continue to work on the sketch The basic requirement is that all relevant data about the sketch must be saved in the file so that the sketch can be exactly restored when the file is read by the program The new version of the program can be found in the source code file SimplePaintWithFiles java A File menu has been added to the new version It contains two sets of Save Open commands one for saving and reloading sketch data in text form and one for data in binary form We will consider both possibilities here in some detail The data for a sketch consists of the background color of the picture and a list of the curves that were drawn by the user A curve consists of a list of Points Point is a standard class in package java awt a Point pt has instance variables pt x and pt y of type int that represent the pixel coordinates of a point on the xy plane Each curve can be a different color Furthermore a curve can be symmetric which means that in addition to the curve itself the horizontal and vertical reflections of the curve are also drawn The data for each curve is stored in an object of type CurveData which is defined in the program as An object of type CurveData represents the data required to redraw one of the curves that have been sketched by the user private static class CurveData implements Serializable Color color The color of the curve boolean symmetric Are horizontal and vertical reflections also drawn ArrayList Point points The points on the curve Then a list of type ArrayList CurveData is used to hold data for all of the curves that the user has drawn Note that in the new version of the program the CurveData class has been declared to implement Serializable This allows objects of type CurveData to be written in binary form to an ObjectOutputStream See Subsection 11 1 6 Let s think about how the data for a sketch could be saved to an ObjectOuputStream The sketch is displayed on the screen in an object of type SimplePaintPanel which is a subclass of JPanel All the data needed for the sketch is stored in instance variables of that object One possibility would be to simply write the entire SimplePaintPanel component as a single object to the stream This could be done in a method in the SimplePaintPanel class with the statement outputStream writeObject this where outputStream is the ObjectOutputStream and this refers to the SimplePaintPanel itself This statement saves the entire current state of the panel To read the data back into the program you would create an ObjectInputStream for reading the object from the file and you would retrieve the object from the file with the statement SimplePaintPanel newPanel SimplePaintPanel in readObject where in is the ObjectInputStream Note that the type cast is necessary because the method in readObject returns a value of type Object To get the saved sketch to appear on the screen the newPanel must replace the current content pane in the program s window furthermore the menu bar of the window must be replaced because the menus are associated with a particular SimplePaintPanel object It might look tempting to be able to save data and restore it with a single command but in this case it s not a good idea The main problem with doing things this way is that the serialized form of objects that represent Swing components can change from one version of Java to the next This means that data files that contain serialized components such as a SimplePaintPanel might become unusable in the future and the data that they contain will be effectively lost This is an important consideration for any serious application Taking this into consideration my program uses a different format when it creates a binary file The data written to the file consists of 1 the background color of the sketch 2 the number of curves in the sketch and 3 all the CurveData objects that describe the individual curves The method that saves the data is similar to the writeFile method from Subsection 11 2 3 Here is the complete doSaveAsBinary method from SimplePaintWithFiles with the changes from the generic writeFile method shown in red Save the user s sketch to a file in binary form as serialized objects using an ObjectOutputStream Files created by this method can be read back into the program using the doOpenAsBinary method private void doSaveAsBinary if fileDialog null fileDialog new JFileChooser File selectedFile Initially selected file name in the dialog if editFile null selectedFile new File sketchData binary else selectedFile new File editFile getName fileDialog setSelectedFile selectedFile fileDialog setDialogTitle Select File to be Saved int option fileDialog showSaveDialog this if option JFileChooser APPROVE OPTION return User canceled or clicked the dialog s close box selectedFile fileDialog getSelectedFile if selectedFile exists Ask the user whether to replace the file int response JOptionPane showConfirmDialog this The file selectedFile getName already exists nDo you want to replace it Confirm Save JOptionPane YES NO OPTION JOptionPane WARNING MESSAGE if response JOptionPane YES OPTION return User does not want to replace the file ObjectOutputStream out try FileOutputStream stream new FileOutputStream selectedFile out new ObjectOutputStream stream catch Exception e JOptionPane showMessageDialog this Sorry but an error occurred while trying to open the file n e return try out writeObject getBackground out writeInt curves size for CurveData curve curves out writeObject curve out flush out close editFile selectedFile setTitle SimplePaint editFile getName catch Exception e JOptionPane showMessageDialog this Sorry but an error occurred while trying to write the file n e The heart of this method consists of the following lines which do the actual writing of the data to the file out writeObject getBackground Writes the panel s background color out writeInt curves size Writes the number of curves for CurveData curve curves For each curve out writeObject curve write the corresponding CurveData object The last line depends on the fact that the CurveData class implements the Serializable interface So does the first the Color class like many of Java s standard classes implements Serializable The doOpenAsBinary method which is responsible for reading sketch data back into the program from an ObjectInputStream has to read exactly the same data that was written in the same order and use that data to build the data structures that will represent the sketch while the program is running Once the data structures have been successfully built they replace the data structures that describe the previous contents of the panel This is done as follows Read data from the file into local variables Color newBackgroundColor Color in readObject int curveCount in readInt ArrayList CurveData newCurves new ArrayList CurveData for int i 0 i curveCount i newCurves add CurveData in readObject in close Copy the data that was read into the instance variables that describe the sketch that is displayed by the program curves newCurves setBackground newBackgroundColor repaint This is only a little harder than saving the entire SimplePaintPanel component to the file in one step and it is more robust since the serialized form of the objects that are saved to file is unlikely to change in the future But it still suffers from the general fragility of binary data An alternative to using object streams is to save the data in human readable character form The basic idea is the same All the data necessary to reconstitute a sketch must be saved to the output file in some definite format The method that reads the file must follow exactly the same format as it reads the data and it must use the data to rebuild the data structures that represent the sketch while the program is running When writing character data we can t write out entire objects in one step All the data has to be expressed ultimately in terms of simple data values such as strings and primitive type values A color for example can be expressed in terms of three integers giving the red green and blue components of the color The first not very good idea that comes to mind might be to just dump all the necessary data in some definite order into the file Suppose that out is a PrintWriter that is used to write to the file We could then say Color bgColor getBackground Write the background color to the file out println bgColor getRed out println bgColor getGreen out println bgColor getBlue out println curves size Write the number of curves for CurveData curve curves For each curve write out println curve color getRed the color of the curve out println curve color getGreen out println curve color getBlue out println curve symmetric 0 1 the curve s symmetry property out println curve points size the number of points on curve for Point pt curve points the coordinates of each point out println pt x out println pt y This works in the sense that the file reading method can read the data and rebuild the data structures Suppose that the input method uses a Scanner named scanner to read the data file Then it could say Color newBackgroundColor Read the background Color int red scanner nextInt int green scanner nextInt int blue scanner nextInt newBackgroundColor new Color red green blue ArrayList CurveData newCurves new ArrayList CurveData int curveCount scanner nextInt The

    Original URL path: http://math.hws.edu/javanotes/c11/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 11.4 -- Networking
    program at the other end of the network connection When that program reads data from its input stream it is receiving the data that was transmitted to it over the network The hard part then is making a network connection in the first place Two sockets are involved To get things started one program must create a socket that will wait passively until a connection request comes in from another socket The waiting socket is said to be listening for a connection On the other side of the connection to be another program creates a socket that sends out a connection request to the listening socket When the listening socket receives the connection request it responds and the connection is established Once that is done each program can obtain an input stream and an output stream for sending data over the connection Communication takes place through these streams until one program or the other closes the connection A program that creates a listening socket is sometimes said to be a server and the socket is called a server socket A program that connects to a server is called a client and the socket that it uses to make a connection is called a client socket The idea is that the server is out there somewhere on the network waiting for a connection request from some client The server can be thought of as offering some kind of service and the client gets access to that service by connecting to the server This is called the client server model of network communication In many actual applications a server program can provide connections to several clients at the same time When a client connects to a server s listening socket that socket does not stop listening Instead it continues listening for additional client connections at the same time that the first client is being serviced To do this it is necessary to use threads We ll look at how it works in the next chapter The URL class that was discussed at the beginning of this section uses a client socket behind the scenes to do any necessary network communication On the other side of that connection is a server program that accepts a connection request from the URL object reads a request from that object for some particular file on the server computer and responds by transmitting the contents of that file over the network back to the URL object After transmitting the data the server closes the connection A client program has to have some way to specify which computer among all those on the network it wants to communicate with Every computer on the Internet has an IP address which identifies it Many computers can also be referred to by domain names such as math hws edu or www whitehouse gov See Section 1 7 Traditional or IPv4 IP addresses are 32 bit integers They are usually written in the so called dotted decimal form such as 64 89 144 135 where each of the four numbers in the address represents an 8 bit integer in the range 0 through 255 A new version of the Internet Protocol IPv6 is currently being introduced IPv6 addresses are 128 bit integers and are usually written in hexadecimal form with some colons and maybe some extra information thrown in In actual use IPv6 addresses are still fairly rare A computer can have several IP addresses and can have both IPv4 and IPv6 addresses Usually one of these is the loopback address which can be used when a program wants to communicate with another program on the same computer The loopback address has IPv4 address 127 0 0 1 and can also in general be referred to using the domain name localhost In addition there can be one or more IP addresses associated with physical network connections Your computer probably has some utility for displaying your computer s IP addresses I have written a small Java program ShowMyNetwork java that does the same thing When I run ShowMyNetwork on my computer the output is en1 192 168 1 47 fe80 0 0 0 211 24ff fe9c 5271 5 lo0 127 0 0 1 fe80 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 The first thing on each line is a network interface name which is really meaningful only to the computer s operating system The same line also contains the IP addresses for that interface In this example lo0 refers to the loopback address which has IPv4 address 127 0 0 1 as usual The most important number here is 192 168 1 47 which is the IPv4 address that can be used for communication over the network The slashes at the start of each address are not part of the actual address The other numbers in the output are IPv6 addresses Now a single computer might have several programs doing network communication at the same time or one program communicating with several other computers To allow for this possibility a network connection actually has a port number in combination with an IP address A port number is just a 16 bit positive integer A server does not simply listen for connections it listens for connections on a particular port A potential client must know both the Internet address or domain name of the computer on which the server is running and the port number on which the server is listening A Web server for example generally listens for connections on port 80 other standard Internet services also have standard port numbers The standard port numbers are all less than 1024 and are reserved for particular services If you create your own server programs you should use port numbers greater than 1024 11 4 3 Sockets in Java To implement TCP IP connections the java net package provides two classes ServerSocket and Socket A ServerSocket represents a listening socket that waits for connection requests from clients A Socket represents one endpoint of an actual network connection A Socket can be a client socket that sends a connection request to a server But a Socket can also be created by a server to handle a connection request from a client This allows the server to create multiple sockets and handle multiple connections A ServerSocket does not itself participate in connections it just listens for connection requests and creates Sockets to handle the actual connections When you construct a ServerSocket object you have to specify the port number on which the server will listen The specification for the constructor is public ServerSocket int port throws IOException The port number must be in the range 0 through 65535 and should generally be greater than 1024 The constructor might throw a SecurityException if a smaller port number is specified An IOException can occur if for example the specified port number is already in use A parameter value of 0 in this method tells the server socket to listen on any available port As soon as a ServerSocket is created it starts listening for connection requests The accept method in the ServerSocket class accepts such a request establishes a connection with the client and returns a Socket that can be used for communication with the client The accept method has the form public Socket accept throws IOException When you call the accept method it will not return until a connection request is received or until some error occurs The method is said to block while waiting for the connection While the method is blocked the program or more exactly the thread that called the method can t do anything else If there are other threads in the same program they can proceed You can call accept repeatedly to accept multiple connection requests The ServerSocket will continue listening for connections until it is closed using its close method or until some error occurs or until the program is terminated in some way Suppose that you want a server to listen on port 1728 and that you want it to continue to accept connections as long as the program is running Suppose that you ve written a method provideService Socket to handle the communication with one client Then the basic form of the server program would be try ServerSocket server new ServerSocket 1728 while true Socket connection server accept provideService connection catch IOException e System out println Server shut down with error e On the client side a client socket is created using a constructor in the Socket class To connect to a server on a known computer and port you would use the constructor public Socket String computer int port throws IOException The first parameter can be either an IP number or a domain name This constructor will block until the connection is established or until an error occurs Once you have a connected socket no matter how it was created you can use the Socket methods getInputStream and getOutputStream to obtain streams that can be used for communication over the connection These methods return objects of type InputStream and OutputStream respectively Keeping all this in mind here is the outline of a method for working with a client connection Open a client connection to a specified server computer and port number on the server and then do communication through the connection void doClientConnection String computerName int serverPort Socket connection InputStream in OutputStream out try connection new Socket computerName serverPort in connection getInputStream out connection getOutputStream catch IOException e System out println Attempt to create connection failed with error e return Use the streams in and out to communicate with the server try connection close Alternatively you might depend on the server to close the connection catch IOException e end doClientConnection All this makes network communication sound easier than it really is And if you think it sounded hard then it s even harder If networks were completely reliable things would be almost as easy as I ve described The problem though is to write robust programs that can deal with network and human error I won t go into detail here However what I ve covered here should give you the basic ideas of network programming and it is enough to write some simple network applications Let s look at a few working examples of client server programming 11 4 4 A Trivial Client Server The first example consists of two programs The source code files for the programs are DateClient java and DateServer java One is a simple network client and the other is a matching server The client makes a connection to the server reads one line of text from the server and displays that text on the screen The text sent by the server consists of the current date and time on the computer where the server is running In order to open a connection the client must know the computer on which the server is running and the port on which it is listening The server listens on port number 32007 The port number could be anything between 1025 and 65535 as long as the server and the client use the same port Port numbers between 1 and 1024 are reserved for standard services and should not be used for other servers The name or IP number of the computer on which the server is running can be specified as a command line argument For example if the server is running on a computer named math hws edu then you could run the client with the command java DateClient math hws edu If a computer is not specified on the command line then the user is prompted to enter one Here is the complete client program import java net import java util Scanner import java io This program opens a connection to a computer specified as the first command line argument If no command line argument is given it prompts the user for a computer to connect to The connection is made to the port specified by LISTENING PORT The program reads one line of text from the connection and then closes the connection It displays the text that it read on standard output This program is meant to be used with the server program DataServer which sends the current date and time on the computer where the server is running public class DateClient public static final int LISTENING PORT 32007 public static void main String args String hostName Name of the server computer to connect to Socket connection A socket for communicating with server BufferedReader incoming For reading data from the connection Get computer name from command line if args length 0 hostName args 0 else Scanner stdin new Scanner System in System out print Enter computer name or IP address hostName stdin nextLine Make the connection then read and display a line of text try connection new Socket hostName LISTENING PORT incoming new BufferedReader new InputStreamReader connection getInputStream String lineFromServer incoming readLine if lineFromServer null A null from incoming readLine indicates that end of stream was encountered throw new IOException Connection was opened but server did not send any data System out println System out println lineFromServer System out println incoming close catch Exception e System out println Error e end main end class DateClient Note that all the communication with the server is done in a try catch statement This will catch the IOExceptions that can be generated when the connection is opened or closed and when data is read from the input stream The connection s input stream is wrapped in a BufferedReader which has a readLine method that makes it easy to read one line of text See Subsection 11 1 4 In order for this program to run without error the server program must be running on the computer to which the client tries to connect By the way it s possible to run the client and the server program on the same computer For example you can open two command windows start the server in one window and then run the client in the other window To make things like this easier most computers will recognize the domain name localhost and the IP number 127 0 0 1 as referring to this computer This means that the command java DateClient localhost will tell the DateClient program to connect to a server running on the same computer If that command doesn t work try java DateClient 127 0 0 1 The server program that corresponds to the DateClient client program is called DateServer The DateServer program creates a ServerSocket to listen for connection requests on port 32007 After the listening socket is created the server will enter an infinite loop in which it accepts and processes connections This will continue until the program is killed in some way for example by typing a CONTROL C in the command window where the server is running When a connection request is received from a client the server calls a subroutine to handle the connection In the subroutine any Exception that occurs is caught so that it will not crash the server Just because a connection to one client has failed for some reason it does not mean that the server should be shut down the error might have been the fault of the client The connection handling subroutine creates a PrintWriter for sending data over the connection It writes the current date and time to this stream and then closes the connection The standard class java util Date is used to obtain the current time An object of type Date represents a particular date and time The default constructor new Date creates an object that represents the time when the object is created The complete server program is as follows import java net import java io import java util Date This program is a server that takes connection requests on the port specified by the constant LISTENING PORT When a connection is opened the program sends the current time to the connected socket The program will continue to receive and process connections until it is killed by a CONTROL C for example Note that this server processes each connection as it is received rather than creating a separate thread to process the connection public class DateServer public static final int LISTENING PORT 32007 public static void main String args ServerSocket listener Listens for incoming connections Socket connection For communication with the connecting program Accept and process connections forever or until some error occurs Note that errors that occur while communicating with a connected program are caught and handled in the sendDate routine so they will not crash the server try listener new ServerSocket LISTENING PORT System out println Listening on port LISTENING PORT while true Accept next connection request and handle it connection listener accept sendDate connection catch Exception e System out println Sorry the server has shut down System out println Error e return end main The parameter client is a socket that is already connected to another program Get an output stream for the connection send the current time and close the connection private static void sendDate Socket client try System out println Connection from client getInetAddress toString Date now new Date The current date and time PrintWriter outgoing Stream for sending data outgoing new PrintWriter client getOutputStream outgoing println now toString outgoing flush Make sure the data is actually sent client close catch Exception e System out println Error e end sendDate end class DateServer When you run DateServer in a command line interface it will sit and wait for connection requests and report them as they are received To make the DateServer service permanently available on a computer the program would be run as a daemon A daemon is a program that runs continually on a computer independently of any user The computer can be configured to start the daemon automatically as soon as the computer boots

    Original URL path: http://math.hws.edu/javanotes/c11/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 12.1 -- Introduction to Threads
    that is done is not important for our purposes here This is a demo program it would be silly in a real program to have multiple threads that do the same thing This computation should take no more than a few seconds on a modern computer The threads that perform this task are defined by the following static nested class When a thread belonging to this class is run it will count the number of primes between 2 and 5000000 It will print the result to standard output along with its ID number and the elapsed time between the start and the end of the computation private static class CountPrimesThread extends Thread int id An id number for this thread specified in the constructor public CountPrimesThread int id this id id public void run long startTime System currentTimeMillis int count countPrimes 2 5000000 Counts the primes long elapsedTime System currentTimeMillis startTime System out println Thread id counted count primes in elapsedTime 1000 0 seconds The main program asks the user how many threads to run and then creates and starts the specified number of threads public static void main String args int numberOfThreads 0 while numberOfThreads 1 numberOfThreads 25 System out print How many threads do you want to use 1 to 25 numberOfThreads TextIO getlnInt if numberOfThreads 1 numberOfThreads 25 System out println Please enter a number between 1 and 25 System out println nCreating numberOfThreads prime counting threads CountPrimesThread worker new CountPrimesThread numberOfThreads for int i 0 i numberOfThreads i worker i new CountPrimesThread i for int i 0 i numberOfThreads i worker i start System out println Threads have been created and started It would be a good idea for you to compile and run the program When I ran the program with one thread on my computer it took 6 251 seconds for the computer to do the computation When I ran it using eight threads the output was Creating 8 prime counting threads Threads have been created and started Thread 4 counted 348513 primes in 12 264 seconds Thread 2 counted 348513 primes in 12 569 seconds Thread 3 counted 348513 primes in 12 567 seconds Thread 0 counted 348513 primes in 12 569 seconds Thread 7 counted 348513 primes in 12 562 seconds Thread 5 counted 348513 primes in 12 565 seconds Thread 1 counted 348513 primes in 12 569 seconds Thread 6 counted 348513 primes in 12 563 seconds The second line was printed immediately after the first At this point the main program has ended but the eight threads continue to run After a pause of about 12 5 seconds all eight threads completed at about the same time The order in which the threads complete is not the same as the order in which they were started and the order is indeterminate That is if the program is run again the order in which the threads complete will probably be different On this computer eight threads took about twice as long as one thread This is because the computer has four processors With eight threads running on four processors one half processor per thread each thread was only actively being executed for about half of the time so it took twice as long to finish its task On a single processor computer eight threads would take about eight times as long as one thread On a computer with eight or more processors eight threads might take no more time than a single thread Because of overhead and other reasons the actual speedup will probably be a little smaller than this analysis indicates but on a multiprocessor machine you should see a definite speedup What happens when you run the program on your own computer How many processors do you have Whenever there are more threads to be run than there are processors to run them the computer divides its attention among all the runnable threads by switching rapidly from one thread to another That is each processor runs one thread for a while then switches to another thread and runs that one for a while and so on Typically these context switches occur about 100 times or more per second The result is that the computer makes progress on all the tasks and it looks to the user as if all the tasks are being executed simultaneously This is why in the sample program in which each thread has the same amount of work to do all the threads complete at about the same time Over any time period longer than a fraction of a second the computer s time is divided approximately equally among all the threads 12 1 2 Operations on Threads Much of Java s thread API can be found in the Thread class However we ll start with a thread related method in Runtime a class that allows a Java program to get information about the environment in which it is running When you do parallel programming in order to spread the work among several processors you might want to take into account the number of available processors You might for example want to create one thread for each processor In Java you can find out the number of processors by calling the function Runtime getRuntime availableProcessors which returns an int giving the number of processors that are available to the Java Virtual Machine In some cases this might be less than the actual number of processors in the computer A Thread object contains several useful methods for working with threads Most important is the start method which was discussed above Once a thread has been started it will continue to run until its run method ends for some reason Sometimes it s useful for one thread to be able to tell whether another thread has terminated If thrd is an object of type Thread then the boolean valued function thrd isAlive can be used to test whether or not thrd has terminated A thread is alive between the time it is started and the time when it terminates After the thread has terminated it is said to be dead The rather gruesome metaphor is also used when we refer to killing or aborting a thread Remember that a thread that has terminated cannot be restarted The static method Thread sleep milliseconds causes the thread that executes this method to sleep for the specified number of milliseconds A sleeping thread is still alive but it is not running While a thread is sleeping the computer can work on any other runnable threads or on other programs Thread sleep can be used to insert a pause in the execution of a thread The sleep method can throw an exception of type InterruptedException which is a checked exception that requires mandatory exception handling In practice this means that the sleep method is usually called inside a try catch statement that catches the potential InterruptedException try Thread sleep lengthOfPause catch InterruptedException e One thread can interrupt another thread to wake it up when it is sleeping or paused for certain other reasons A Thread thrd can be interrupted by calling the method thrd interrupt Doing so can be a convenient way to send a signal from one thread to another A thread knows it has been interrupted when it catches an InterruptedException Outside any catch handler for the exception the thread can check whether it has been interrupted by calling the static method Thread interrupted This method tells whether the current thread the thread that executes the method has been interrupted It also has the unusual property of clearing the interrupted status of the thread so you only get one chance to check for an interruption In your own programs your threads are not going to be interrupted unless you interrupt them So most often you are not likely to need to do anything in response to an InterruptedException except to catch it Sometimes it s necessary for one thread to wait for another thread to die This is done with the join method from the Thread class Suppose that thrd is a Thread Then if another thread calls thrd join that other thread will go to sleep until thrd terminates If thrd is already dead when thrd join is called then it simply has no effect The join method can throw an InterruptedException which must be handled as usual As an example the following code starts several threads waits for them all to terminate and then outputs the elapsed time CountPrimesThread worker new CountPrimesThread numberOfThreads long startTime System currentTimeMillis for int i 0 i numberOfThreads i worker i new CountPrimesThread worker i start for int i 0 i numberOfThreads i try worker i join Wait until worker i finishes if it hasn t already catch InterruptedException e At this point all the worker threads have terminated long elapsedTime System currentTimeMillis startTime System out println Total elapsed time elapsedTime 1000 0 seconds An observant reader will note that this code assumes that no InterruptedException will occur To be absolutely sure that the thread worker i has terminated in an environment where InterruptedExceptions are possible you would have to do something like while worker i isAlive try worker i join catch InterruptedException e Another version of the join method takes an integer parameter that specifies the maximum number of milliseconds to wait A call to thrd join m will wait until either thrd has terminated or until m milliseconds have elapsed This can be used to allow a thread to wake up occasionally to perform some task while it is waiting Here for example is a code segment that will start a thread thrd and then will output a period every two seconds as long as thrd continues to run System out print Running the thread thrd start while thrd isAlive try thrd join 2000 System out print catch InterruptedException e System out println Done Threads have two properties that are occasionally useful a daemon status and a priority A Thread thrd can be designated as a daemon thread by calling thrd setDaemon true This must be done before the thread is started and it can throw an exception of type SecurityException if the calling thread is not allowed to modify thrd s properties This has only one effect The Java Virtual Machine will exit as soon as there are no non daemon threads that are still alive That is the fact that a daemon thread is still alive is not enough to keep the Java Virtual Machine running A daemon thread might exist for example only to provide some service to other non daemon threads When there are no more non daemon threads there will be no further call for the daemon thread s services so the program might as well shut down The priority of a thread is a more important property Every thread has a priority specified as an integer A thread with a greater priority value will be run in preference to a thread with a smaller priority For example computations that can be done in the background when no more important thread has work to do can be run with a low priority In the next section we will see how this can be useful in GUI programs If thrd is of type Thread then thrd getPriority returns the integer that specifies thrd s priority and thrd setPriority p can be used to set its priority to a given integer p Priorities cannot be arbitrary integers and thrd setPriority will throw an IllegalArgumentException if the specified priority is not in the legal range for the thread The range of legal priority values can differ from one computer to another The range of legal values is specified by the constants Thread MIN PRIORITY and Thread MAX PRIORITY but a given thread might be further restricted to values less than Thread MAX PRIORITY The default priority is given by Thread NORM PRIORITY To set thrd to run with a priority value just below the normal priority you can call thrd setPriority Thread NORM PRIORITY 1 Note that thrd setPriority can also throw an exception of type SecurityException if the thread that calls the method is not allowed to set the priority of thrd Finally I ll note that the static method Thread currentThread returns the current thread That is the return value of this method is the thread that executed the method This allows a thread to get a reference to itself so that it can modify its own properties For example you can determine the priority of the currently running thread by calling Thread currentThread getPriority 12 1 3 Mutual Exclusion with synchronized It s pretty easy to program several threads to carry out completely independent tasks The real difficulty arises when threads have to interact in some way One way that threads interact is by sharing resources When two threads need access to the same resource such as a variable or a window on the screen some care must be taken that they don t try to use the same resource at the same time Otherwise the situation could be something like this Imagine several cooks sharing the use of just one measuring cup and imagine that Cook A fills the measuring cup with milk only to have Cook B grab the cup before Cook A has a chance to empty the milk into his bowl There has to be some way for Cook A to claim exclusive rights to the cup while he performs the two operations Add Milk To Cup and Empty Cup Into Bowl Something similar happens with threads even with something as simple as adding one to a counter The statement count count 1 is actually a sequence of three operations Step 1 Get the value of count Step 2 Add 1 to the value Step 3 Store the new value in count Suppose that each of several threads performs these three steps Remember that it s possible for two threads to run at the same time and even if there is only one processor it s possible for that processor to switch from one thread to another at any point Suppose that while one thread is between Step 2 and Step 3 another thread starts executing the same sequence of steps Since the first thread has not yet stored the new value in count the second thread reads the old value of count and adds one to that old value Both threads have computed the same new value for count and both threads then go on to store that value back into count by executing Step 3 After both threads have done so the value of count has gone up only by 1 instead of by 2 This type of problem is called a race condition This occurs when one thread is in the middle of a multi step operation and another thread can change some value or condition that the first thread is depending upon The first thread is in a race to complete all the steps before it is interrupted by another thread Another example of a race condition can occur in an if statement Consider the following statement which is meant to avoid a division by zero error if A 0 B C A Suppose that this statement is executed by some thread If the variable A is shared by one or more other threads and if nothing is done to guard against the race condition then it is possible that one of those other threads will change the value of A to zero between the time that the first thread checks the condition A 0 and the time that it does the division This means that the thread can end up dividing by zero even though it just checked that A was not zero To fix the problem of race conditions there has to be some way for a thread to get exclusive access to a shared resource This is not a trivial thing to implement but Java provides a high level and relatively easy to use approach to exclusive access It s done with synchronized methods and with the synchronized statement These are used to protect shared resources by making sure that only one thread at a time will try to access the resource Synchronization in Java actually provides only mutual exclusion which means that exclusive access to a resource is only guaranteed if every thread that needs access to that resource uses synchronization Synchronization is like a cook leaving a note that says I m using the measuring cup This will get the cook exclusive access to the cup but only if all the cooks agree to check the note before trying to grab the cup Because this is a difficult topic I will start with a simple example Suppose that we want to avoid the race condition that occurs when several threads all want to add 1 to a counter We can do this by defining a class to represent the counter and by using synchronized methods in that class A method is declared to be synchronized by adding the reserved word synchronized as a modifier to the definition of the method public class ThreadSafeCounter private int count 0 The value of the counter synchronized public void increment count count 1 synchronized public int getValue return count If tsc is of type ThreadSafeCounter then any thread can call tsc increment to add 1 to the counter in a completely safe way The fact that tsc increment is synchronized means that only one thread can be in this method at a time once a thread starts executing this method it is guaranteed that it will finish executing it without having another thread change the value of tsc count in the meantime There is no possibility of a race condition Note that the guarantee depends on the fact that count is a private variable This forces

    Original URL path: http://math.hws.edu/javanotes/c12/s1.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 12.4 -- Threads and Networking
    closed since the error might be the expected error that is generated when a socket is closed if state ConnectionState CLOSED postMessage n n ERROR e finally Clean up before terminating the thread cleanUp This method calls several other methods to do some of its work but you can see the general outline of how it works After opening the connection as either a server or client the run method enters a while loop in which it receives and processes messages from the other side of the connection until the connection is closed It is important to understand how the connection can be closed The GUIChat window has a Disconnect button that the user can click to close the connection The program responds to this event by closing the socket that represents the connection and by setting the connection state to CLOSED It is likely that when this happens the connection handling thread is blocked in the in readLine method waiting for an incoming message When the socket is closed by the GUI thread this method will fail and will throw an exception this exception causes the thread to terminate If the connection handling thread happens to be between calls to in readLine when the socket is closed the while loop will terminate because the connection state changes from CONNECTED to CLOSED Note that closing the window will also close the connection in the same way It is also possible for the user on the other side of the connection to close the connection When that happens the stream of incoming messages ends and the in readLine on this side of the connection returns the value null which indicates end of stream and acts as a signal that the connection has been closed by the remote user For a final look into the GUIChat code consider the methods that send and receive messages These methods are called from different threads The send method is called by the event handling thread in response to a user action Its purpose is to transmit a message to the remote user It is conceivable though not likely that the data output operation could block if the socket s output buffer fills up A more sophisticated program might take this possibility into account This method uses a PrintWriter out that writes to the socket s output stream Synchronization of this method prevents the connection state from changing in the middle of the send operation Send a message to the other side of the connection and post the message to the transcript This should only be called when the connection state is ConnectionState CONNECTED if it is called at other times it is ignored synchronized void send String message if state ConnectionState CONNECTED postMessage SEND message out println message out flush if out checkError postMessage nERROR OCCURRED WHILE TRYING TO SEND DATA close Closes the connection The received method is called by the connection handling thread after a message has been read from the remote user Its only job is to display the message to the user but again it is synchronized to avoid the race condition that could occur if the connection state were changed by another thread while this method is being executed This is called by the run method when a message is received from the other side of the connection The message is posted to the transcript but only if the connection state is CONNECTED This is because a message might be received after the user has clicked the Disconnect button that message should not be seen by the user synchronized private void received String message if state ConnectionState CONNECTED postMessage RECEIVE message 12 4 3 A Threaded Network Server Threads are often used in network server programs They allow the server to deal with several clients at the same time When a client can stay connected for an extended period of time other clients shouldn t have to wait for service Even if the interaction with each client is expected to be very brief you can t always assume that that will be the case You have to allow for the possibility of a misbehaving client one that stays connected without sending data that the server expects This can hang up a thread indefinitely but in a threaded server there will be other threads that can carry on with other clients The DateServer java sample program from Subsection 11 4 4 is an extremely simple network server program It does not use threads so the server must finish with one client before it can accept a connection from another client Let s see how we can turn DateServer into a threaded server This server is so simple that doing so doesn t make a great deal of sense However the same techniques will work for more complicated servers See for example Exercise 12 4 As a first attempt consider DateServerWithThreads java This sample program creates a new thread every time a connection request is received instead of handling the connection itself by calling a subroutine The main program simply creates the thread and hands the connection to the thread This takes very little time and in particular will not block The run method of the thread handles the connection in exactly the same way that it would be handled by the original program This is not at all difficult to program Here s the new version of the program with significant changes shown in red Note again that the constructor for the connection thread does very little and in particular cannot block this is very important since the constructor runs in the main thread import java net import java io import java util Date This program is a server that takes connection requests on the port specified by the constant LISTENING PORT When a connection is opened the program sends the current time to the connected socket The program will continue to receive and process connections until it is killed by a CONTROL C for example This version of the program creates a new thread for every connection request public class DateServerWithThreads public static final int LISTENING PORT 32007 public static void main String args ServerSocket listener Listens for incoming connections Socket connection For communication with the connecting program Accept and process connections forever or until some error occurs try listener new ServerSocket LISTENING PORT System out println Listening on port LISTENING PORT while true Accept next connection request and create thread to handle it connection listener accept ConnectionHandler handler new ConnectionHandler connection handler start catch Exception e System out println Sorry the server has shut down System out println Error e return end main Defines a thread that handles the connection with one client private static class ConnectionHandler extends Thread Socket client The connection to the client ConnectionHandler Socket socket client socket public void run code copied from the original DataServer program String clientAddress client getInetAddress toString try System out println Connection from clientAddress Date now new Date The current date and time PrintWriter outgoing Stream for sending data outgoing new PrintWriter client getOutputStream outgoing println now toString outgoing flush Make sure the data is actually sent client close catch Exception e System out println Error on connection with clientAddress e end class DateServerWithThreads One interesting change is at the end of the run method where I ve added the clientAddress to the output of the error message I did this to identify which connection the error message refers to Since threads run in parallel it s possible for outputs from different threads to be intermingled in various orders Messages from the same thread don t necessarily come together in the output they might be separated by messages from other threads This is just one of the complications that you have to keep in mind when working with threads 12 4 4 Using a Thread Pool It s not very efficient to create a new thread for every connection especially when the connections are typically very short lived Fortunately we have an alternative thread pools Subsection 12 3 2 DateServerWithThreadPool java is an improved version of our server that uses a thread pool Each thread in the pool runs in an infinite loop Each time through the loop it handles one connection We need a way for the main program to send connections to the threads It s natural to use a blocking queue named connectionQueue for that purpose A connection handling thread takes connections from this queue Since it is blocking queue the thread blocks when the queue is empty and wakes up when a connection becomes available in the queue No other synchronization or communication technique is needed it s all built into the blocking queue Here is the run method for the connection handling threads public void run while true Socket client try client connectionQueue take Blocks until item is available catch InterruptedException e continue If interrupted just go back to start of while loop String clientAddress client getInetAddress toString try System out println Connection from clientAddress System out println Handled by thread this Date now new Date The current date and time PrintWriter outgoing Stream for sending data outgoing new PrintWriter client getOutputStream outgoing println now toString outgoing flush Make sure the data is actually sent client close catch Exception e System out println Error on connection with clientAddress e The main program in the meantime runs in an infinite loop in which connections are accepted and added to the queue while true Accept next connection request and put it in the queue connection listener accept try connectionQueue put connection Blocks if queue is full catch InterruptedException e The queue in this program is of type ArrayBlockingQueue Socket As such it has a limited capacity and the put operation on the queue will block if the queue is full But wait didn t we want to avoid blocking the main program When the main program is blocked the server is no longer accepting connections and clients who are trying to connect are kept waiting Would it be better to use a LinkedBlockingQueue with an unlimited capacity In fact connections in the blocking queue are waiting anyway they are not being serviced If the queue grows unreasonably long connections in the queue will have to wait for an unreasonable amount of time If the queue keeps growing indefinitely that just means that the server is receiving connection requests faster than it can process them That could happen for several reasons Your server might simply not be powerful enough to handle the volume of traffic that you are getting you need to buy a new server Or perhaps the thread pool doesn t have enough threads to fully utilize your server you should increase the size of the thread pool to match the server s capabilities Or maybe your server is under a Denial Of Service attack in which some bad guy is deliberately sending your server more requests than it can handle in an attempt to keep other legitimate clients from getting service In any case ArrayBlockingQueue with limited capacity is the correct choice The queue should be short enough so that connections in the queue will not have to wait too long for service In a real server the size of the queue and the number of threads in the thread pool should be adjusted to tune the server to account for the particular hardware and network on which the server is running and for the nature of the client requests that it typically processes Optimal tuning is in general a difficult problem There is by the way another way that things can go wrong Suppose that the server needs to read some data from the client but the client doesn t send the expected data The thread that is trying to read the data can then block indefinitely waiting for the input If a thread pool is being used this could happen to every thread in the pool In that case no further processing can ever take place The solution to this problem is to have connections time out if they are inactive for an excessive period of time Typically each connection thread will keep track of the time when it last received data from the client The server runs another thread sometimes called a reaper thread after the Grim Reaper that wakes up periodically and checks each connection thread to see how long it has been inactive A connection thread that has been waiting too long for input is terminated and a new thread is started in its place The question of how long the timeout period should be is another difficult tuning issue 12 4 5 Distributed Computing We have seen how threads can be used to do parallel processing where a number of processors work together to complete some task So far we have assumed that all the processors were inside one multi processor computer But parallel processing can also be done using processors that are in different computers as long as those computers are connected to a network over which they can communicate This type of parallel processing in which a number of computers work together on a task and communicate over a network is called distributed computing In some sense the whole Internet is an immense distributed computation but here I am interested in how computers on a network can cooperate to solve some computational problem There are several approaches to distributed computing that are supported in Java RMI and CORBA are standards that enable a program running on one computer to call methods in objects that exist on other computers This makes it possible to design an object oriented program in which different parts of the program are executed on different computers RMI Remote Method Invocation only supports communication between Java objects CORBA Common Object Request Broker Architecture is a more general standard that allows objects written in various programming languages including Java to communicate with each other As is commonly the case in networking there is the problem of locating services where in this case a service means an object that is available to be called over the network That is how can one computer know which computer a service is located on and what port it is listening on RMI and CORBA solve this problem using a request broker a server program running at a known location keeps a list of services that are available on other computers Computers that offer services register those services with the request broker computers that need services must know the location of the broker and they contact it to find out what services are available and where they are located RMI and CORBA are complex systems that are not very easy to use I mention them here because they are part of Java s standard network API but I will not discuss them further Instead we will look at a relatively simple demonstration of distributed computing that uses only basic networking The problem that we will consider is the same one that we used in MultiprocessingDemo1 java and its variations in Section 12 2 and Section 12 3 namely the computation of a complex image This is an application that uses the simplest type of parallel programming in which the problem can be broken down into tasks that can be performed independently with no communication between the tasks To apply distributed computing to this type of problem we can use one master program that divides the problem into tasks and sends those tasks over the network to worker programs that do the actual work The worker programs send their results back to the master program which combines the results from all the tasks into a solution of the overall problem In this context the worker programs are often called slaves and the program uses the so called master slave approach to distributed computing The demonstration program is defined by three source code files CLMandelbrotMaster java defines the master program CLMandelbrotWorker java defines the worker programs and CLMandelbrotTask java defines the class CLMandelbrotTask that represents an individual task that is performed by the workers The master divides the overall problem into a collection of tasks it distributes those tasks to the workers that will execute the tasks and send the results back to the master and the master applies the results from all the individual task to the overall problem To run the demonstration you must first start the CLMandelbrotWorker program on several computers probably by running it on the command line This program uses CLMandelbrotTask so both class files CLMandelbrotWorker class and CLMandelbrotTask class must be present on the worker computers You can then run CLMandelbrotMaster on the master computer Note that this program also requires the class CLMandelbrotTask You must specify the host name or IP address of each of the worker computers as command line arguments for CLMandelbrotMaster The worker programs listen for connection requests from the master program and the master program must be told where to send those requests For example if the worker program is running on three computers with IP addresses 172 21 7 101 172 21 7 102 and 172 21 7 103 then you can run CLMandelbrotMaster with the command java CLMandelbrotMaster 172 21 7 101 172 21 7 102 172 21 7 103 The master will make a network connection to the worker at each IP address these connections will be used for communication between the master program and the workers It is possible to run several copies of CLMandelbrotWorker on the same computer but they must listen for network connections on different ports It is also possible to run CLMandelbrotWorker on the same computer as CLMandelbrotMaster You might even see some speed up when you do this if your computer has several processors See the comments in the program source code files for more information but here are some commands that

    Original URL path: http://math.hws.edu/javanotes/c12/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 1.6 -- The Modern User Interface
    very simple Java program that demonstrates a few standard GUI interface components When the program is run a window similar to the picture shown here will open on the computer screen There are four components in the window with which the user can interact a button a checkbox a text field and a pop up menu These components are labeled There are a few other components in the window The labels themselves are components even though you can t interact with them The right half of the window is a text area component which can display multiple lines of text A scrollbar component appears alongside the text area when the number of lines of text becomes larger than will fit in the text area And in fact in Java terminology the whole window is itself considered to be a component If you would like to run this program the source code GUIDemo java as well as a compiled program GUIDemo jar are available on line For more information on using this and other examples from this textbook see Section 2 6 Now Java actually has two complete sets of GUI components One of these the AWT or Abstract Windowing Toolkit was available in the original version of Java The other which is known as Swing was introduced in Java version 1 2 and is used in preference to the AWT in most modern Java programs The program that is shown above uses components that are part of Swing When a user interacts with GUI components events are generated For example clicking a push button generates an event and pressing return while typing in a text field generates an event Each time an event is generated a message is sent to the program telling it that the event has occurred and

    Original URL path: http://math.hws.edu/javanotes/c1/s6.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.9 -- Introduction to GUI Programming
    all the lines start at x coordinate 100 so we can use the constant 100 as the value for x1 Since the lines are 200 pixels long we can use the constant 300 as the value for x2 The y coordinates of the lines are different but we can see that both endpoints of a line have the same y coordinates so we can use a single variable as the value for y1 and for y2 Using y as the name of that variable the command for drawing one of the lines becomes g drawLine 100 y 300 y The value of y is 50 for the top line and increases by 10 each time we move down from one line to the next We just need to make sure that y takes on the correct sequence of values We can use a for loop that counts from 1 to 10 int y y coordinate for the line int i loop control variable y 50 y starts at 50 for the first line for i 1 i 10 i g drawLine 100 y 300 y y y 10 increase y by 10 before drawing the next line Alternatively we could use y itself as the loop control variable noting that the value of y for the last line is 140 int y for y 50 y 140 y y 10 g drawLine 100 y 300 y If we wanted to set the color of the lines we could do that by calling g setColor before drawing them If we just draw the lines without setting the color they will be black For something a little more complicated let s draw a large number of randomly colored randomly positioned filled circles Since we only know a few colors I will randomly select the color to be red green or blue That can be done with a simple switch statement similar to the ones in Subsection 3 6 4 switch int 3 Math random case 0 g setColor Color RED break case 1 g setColor Color GREEN break case 2 g setColor Color BLUE break I will choose the center points of the circles at random Let s say that the width of the drawing area is given by a variable width Then we want a random value in the range 0 to width 1 for the horizontal position of the center Similarly the vertical position of the center will a random value in the range 0 to height 1 That leaves the size of the circle to be determined I will make the radius of each circle equal to 50 pixels We can draw the circle with a statement of the form g fillOval x y w h However in this command x and y are not the coordinates of the center of the circle they are the upper left corner of a rectangle drawn around the circle To get values for x and y we have to move back from the center of the circle by 50 pixels an amount equal to the radius of the circle The parameters w and h give the width and height of the rectangle which has to be twice the radius or 100 pixels in this case Taking all this into account here is a code segment for drawing a random circle centerX int width Math random centerY int height Math random g fillOval centerX 50 centerY 50 100 100 This code comes after the color setting code given above In the end I found that the picture looks better if I also draw a black outline around each filled circle so I added this code at the end g setColor Color BLACK g drawOval centerX 50 centerY 50 100 100 Finally to get a large number of circles I put all of the above code into a for loop that runs for 500 executions Here s a typical drawing from the program shown at reduced size 3 9 2 Drawing in a Program Now as you know you can t just have a bunch of Java code standing by itself The code has to be inside a subroutine definition that is itself inside a class definition In fact for my circle drawing program the complete subroutine for drawing the picture looks like this public void drawFrame Graphics g int frameNumber int width int height int centerX The x coord of the center of a disk int centerY The y coord of the center of a disk int colorChoice Used to select a random color int count Loop control variable for counting disks for count 0 count 500 count colorChoice int 3 Math random switch colorChoice case 0 g setColor Color RED break case 1 g setColor Color GREEN break case 2 g setColor Color BLUE break centerX int width Math random centerY int height Math random g fillOval centerX 50 centerY 50 100 100 g setColor Color BLACK g drawOval centerX 50 centerY 50 100 100 This is the first subroutine definition that you have seen other than main but you will learn all about defining subroutines in the next chapter The first line of the definition makes available certain values that are used in the subroutine the graphics context g and the width and height of the drawing area Ignore frameNumber for now These values come from outside the subroutine but the subroutine can use them The point here is that to draw something you just have to fill in the inside of the subroutine just as you write a program by filling in the inside of main The subroutine definition still has to go inside a class that defines the program In this case the class is named RandomCircles and the complete program is available in the sample source code file RandomCircles java You can run that program to see the drawing There s a lot in the program that you won t understand To make your own drawing all you

    Original URL path: http://math.hws.edu/javanotes/c3/s9.html (2016-02-07)
    Open archived version from archive