private File subject = null;
private long lastStat[];
-
+ boolean waslocked=false;
boolean exists = false;
/**
if (tl.isLocked()) {
tl.release();
return false;
- } else {
- return true;
}
+ tl.release();
+ return true;
}
return false;
}
+
private long[] getStat(File subject) {
return new long[] { subject.lastModified(), subject.length() };
}
return false;
return true;
}
+ /**
+ * Detect changes in file state and release of any
+ * lock in place during change.
+ * @return true if file state has changed
+ */
private boolean check() {
if (subject != null) {
if (!subject.exists()) {
if (exists) {
- exists = false;
- return true;
+ if (!waslocked) {
+ // !checkLock()) {
+
+ exists = false;
+ // waslocked=false;
+ return true;
+ }
}
+ // locked - state change registered after lock is released
return false;
} else {
-
long[] newStat = getStat(subject); // subject.lastModified();
- if (exists && ((compStat(lastStat, newStat) || checkLock()))) {
+ if (!checkLock()) {
+ // file is free to access, return state change
+ if (!exists || !compStat(lastStat, newStat)) {
+ waslocked=false;
+ exists=true;
+ lastStat=newStat;
+ return true;
+ }
+ // no change
+ return false;
+ } else {
+ waslocked=true;
return false;
}
- lastStat = newStat;
- exists = true;
- return true;
}
}
return false;
}
-
+ public void setState() {
+ if (subject!=null) {
+ lastStat = getStat(subject);
+ exists = subject.exists();
+ waslocked = checkLock();
+ }
+ }
+
public FileWatcher(File subject) {
// TODO Auto-generated constructor stub
this.subject = subject;
- check();
+ setState();
}
public boolean hasChanged() {
public class Lock {
FileLock lock = null;
- RandomAccessFile rafile;
+ RandomAccessFile rafile=null;
/**
* creates a valid Lock (test with <method>isLocked</method>)
* if a lock could be obtained for <param>lockfile</param>
public Lock(java.io.File lockfile) {
// try and get a lock.
lock = null;
-
+
try {
if (!lockfile.exists())
if (!lockfile.createNewFile()) {
e.printStackTrace();
}
}
-
+
boolean isLocked() {
if (lock != null && lock.isValid()) {
return true;
return false;
}
public void release() {
- if (lock!=null) {
- try {
- rafile.close();
+ try {
+ if (lock!=null && lock.isValid())
lock.release();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace(System.err);
- }
+ if (rafile!=null && rafile.getChannel().isOpen())
+ rafile.getChannel().close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace(System.err);
}
+ lock=null;
+ rafile=null;
}
+
/* Explicitly release lock (probably don't need to do this!)
* @see java.lang.Object#finalize()
*/