Java Reference
In-Depth Information
As you can see in the run() method, this code sleeps for five minutes (300 seconds), then
checks whether it should do anything. If the user has turned autosave off, or hasn't made any
changes since the last save, nothing needs to be done. Otherwise, we call the saveFile()
method in the main program, which saves the data to the current file. It would be smarter to
save it to a recovery file of some name, as the better word processors do.
What's not shown is that now all the methods must be synchronized. It's easy to see why if
you think about how the save method would work if the user clicked the Save button at the
same time that the autosave method called it, or if the user clicked Exit while the file save
method had just opened the file for writing. The “save to recovery file” strategy gets around
some of this, but it still needs a great deal of care.
Program: Threaded Network Server
Problem
You want a network server to be multithreaded.
Solution
Either create a thread when you accept a connection or create a pool of threads in advance
and have each wait on the accept() call.
Discussion
Networking (see Chapters 13 and 16 ) and threads are two very powerful APIs that are a
standard part of the Java platform. Used alone, each can increase the reach of your Java pro-
gramming skills. A common paradigm is a threaded network server, which can either preal-
locate a certain number of threads or can start a new thread each time a client connects. The
big advantage is that each thread can block on read without causing other client threads to
delay.
One example of a threaded socket server was discussed in Handling Multiple Clients ; anoth-
er is shown here. It seems to be some kind of rite (or wrong) of passage for Java folks to
write a web server entirely in Java. This one is fairly small and simple; if you want a full-
bodied flavor, check out the Apache Foundation's Apache (written in C) and Tomcat (pure
Java) servers (I may be biased because I coauthored Tomcat: The Definitive Guide
Search WWH ::




Custom Search