01: package com.sun.portal.search.autoclassify;
02:
03: import java.io.*;
04: import java.util.*;
05:
06: /** <p>Title: HeartBeat</p>
07: * <p>Description: This object is used to simulate using pid to avoid multiple
08: * instance running in native program. A heartbeat will periodically touch his
09: * lockfile. A new heartbeat object with same lockfile will exame the existence of
10: * the lockfile when it was constructed. If the lockfile was exist, it will exame
11: * the lastmodified of the file with two beattime period. When the timestamp got
12: * changed, it will throw exception. Otherwise it will take over the ownership of
13: * the lockfile.</p>
14: * <p>Copyright: Copyright (c) 2002</p>
15: * <p>Company: Sun Microsystems</p>
16: * @author Allen Chiang
17: * @version 1.0
18: */
19:
20: public class HeartBeat extends Thread {
21: /** A default beattime. Default to 5 seconds. */
22: public static long beatTime = 5000; //5 sec
23: private FileWriter fw = null;
24: private boolean shouldStop = false;
25: private String lockFileName = null;
26:
27: /** Create a heartbeat action by given lockfile
28: * @param lockFileName A lockfile used in this heartbeat object
29: * @throws Exception Exception caused by opening the lockfile or another heartbeat is running on the
30: * lockfile.
31: */
32: public HeartBeat(String lockFileName)
33: throws HeartBeatFailureException {
34: try {
35: this .lockFileName = lockFileName;
36: File f = new File(lockFileName);
37: long now = new Date().getTime();
38: long lastModified = 0;
39: if (f.exists()) {
40: lastModified = f.lastModified();
41: if (lastModified + beatTime * 2 > now) {
42: sleep(beatTime * 2);
43: if (f.lastModified() > lastModified) {
44: throw new HeartBeatFailureException(
45: "Another process is running");
46: }
47: }
48: }
49: fw = new FileWriter(lockFileName);
50: fw.write(Long.toString(now));
51: } catch (Exception e) {
52: throw new HeartBeatFailureException(e.getMessage());
53: }
54: }
55:
56: /** Stop the heartbeat action */
57: public void Stop() {
58: shouldStop = true;
59: }
60:
61: /** Start the heartbeat action */
62: public void run() {
63: long started = new Date().getTime();
64: while (!shouldStop) {
65: try {
66: long now = new Date().getTime();
67: if (now - started > beatTime) {
68: fw
69: .write(Long.toString(new Date().getTime())
70: + "\n");
71: fw.flush();
72: //System.out.println("Update lock file");
73: started = now;
74: }
75: wait(1000);
76: } catch (InterruptedException e) {
77: System.out.println("HeartBeat Thred being interrupted");
78:
79: } catch (Exception ioe) {
80:
81: }
82: }
83: try {
84: fw.close();
85: File f = new File(lockFileName);
86: f.delete();
87: } catch (IOException fe) {
88:
89: }
90:
91: }
92: }
|