Skip to content

Commit

Permalink
Do not crash application when lock file is broken, refs #131
Browse files Browse the repository at this point in the history
  • Loading branch information
sarxos committed Aug 4, 2013
1 parent d0de4ec commit 32bc81a
Showing 1 changed file with 28 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
Expand Down Expand Up @@ -92,6 +93,7 @@ protected WebcamLock(Webcam webcam) {
super();
this.webcam = webcam;
this.lock = new File(System.getProperty("java.io.tmpdir"), getLockName());
this.lock.deleteOnExit();
}

private String getLockName() {
Expand All @@ -106,7 +108,9 @@ private void write(long value) {
DataOutputStream dos = null;

try {
tmp = File.createTempFile(name, "");

tmp = File.createTempFile(String.format("%s-tmp", name), "");
tmp.deleteOnExit();

dos = new DataOutputStream(new FileOutputStream(tmp));
dos.writeLong(value);
Expand All @@ -130,9 +134,9 @@ private void write(long value) {

if (tmp.renameTo(lock)) {

// rename operation can fail (mostly on Windows), so we simply jump
// out the method if it succeed, or try to rewrite content using
// streams if it fail
// atomic rename operation can fail (mostly on Windows), so we
// simply jump out the method if it succeed, or try to rewrite
// content using streams if it fail

return;
} else {
Expand All @@ -141,7 +145,9 @@ private void write(long value) {

if (!lock.exists()) {
try {
if (!lock.createNewFile()) {
if (lock.createNewFile()) {
LOG.info("Lock file {} for {} has been created", lock, webcam);
} else {
throw new RuntimeException("Not able to create file " + lock);
}
} catch (IOException e) {
Expand All @@ -162,12 +168,14 @@ private void write(long value) {
synchronized (webcam) {
do {
try {

fos = new FileOutputStream(lock);
fis = new FileInputStream(tmp);
while ((n = fis.read(buffer)) != -1) {
fos.write(buffer, 0, n);
}
rewritten = true;

} catch (IOException e) {
LOG.debug("Not able to rewrite lock file", e);
} finally {
Expand Down Expand Up @@ -209,9 +217,16 @@ private long read() {

DataInputStream dis = null;

long value = -1;
boolean broken = false;

synchronized (webcam) {

try {
return (dis = new DataInputStream(new FileInputStream(lock))).readLong();
value = (dis = new DataInputStream(new FileInputStream(lock))).readLong();
} catch (EOFException e) {
LOG.debug("Webcam lock is broken - EOF when reading long variable from stream", e);
broken = true;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
Expand All @@ -223,7 +238,14 @@ private long read() {
}
}
}

if (broken) {
LOG.warn("Lock file {} for {} is broken - recreating it", lock, webcam);
write(-1);
}
}

return value;
}

private void update() {
Expand Down

0 comments on commit 32bc81a

Please sign in to comment.