Java Reference
In-Depth Information
Example 18−2: Counter.java (continued)
// Start counting at 1!
count = new Integer(1);
}
// Store the incremented (or new) counter value into the hashtable
counts.put(counterName, count);
// Check whether saveInterval milliseconds have elapsed since we
// last saved our state. If so, save it again. This prevents
// us from losing more than saveInterval ms of data, even if the
// server crashes unexpectedly.
if (System.currentTimeMillis() - lastSaveTime > saveInterval) {
saveState();
lastSaveTime = System.currentTimeMillis();
}
} // End of synchronized block
// Finally, output the counter value. Since this servlet is usually
// included within the output of other servlets, we don't bother
// setting the content type.
PrintWriter out = response.getWriter();
out.print(count);
}
// The doPost method just calls doGet, so that this servlet can be
// included in pages that are loaded with POST requests
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
doGet(request, response);
}
// Save the state of the counters by serializing the hashtable to
// the file specified by the initialization parameter.
void saveState() throws IOException {
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(countfile)));
out.writeObject(counts); // Save the hashtable to the stream
out.close();
// Always remember to close your files!
}
// Load the initial state of the counters by de-serializing a hashtable
// from the file specified by the initialization parameter. If the file
// doesn't exist yet, then start with an empty hashtable.
void loadState() throws IOException {
if (!countfile.exists()) {
counts = new HashMap();
return;
}
ObjectInputStream in = null;
try {
in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(countfile)));
counts = (HashMap) in.readObject();
}
catch(ClassNotFoundException e) {
throw new IOException("Count file contains bad data: " +
e.getMessage());
Search WWH ::




Custom Search