Skip to content

Commit

Permalink
Synchronize lock read method, refs #131
Browse files Browse the repository at this point in the history
  • Loading branch information
sarxos committed Aug 3, 2013
1 parent 884bee4 commit d0de4ec
Showing 1 changed file with 29 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@

/**
* This class is used as a global (system) lock preventing other processes from
* using the same camera while it's open.
* using the same camera while it's open. Whenever webcam is open there is a
* thread running in background which updates the lock once per 2 seconds. Lock
* is being released whenever webcam is either closed or completely disposed.
* Lock will remain for at least 2 seconds in case when JVM has not been
* gracefully terminated (due to SIGSEGV, SIGTERM, etc).
*
* @author Bartosz Firyn (sarxos)
*/
Expand All @@ -25,8 +29,6 @@ public class WebcamLock {
*/
private static final Logger LOG = LoggerFactory.getLogger(WebcamLock.class);

private static final Object MUTEX = new Object();

/**
* Update interval (ms).
*/
Expand Down Expand Up @@ -66,10 +68,19 @@ public void run() {
*/
private final Webcam webcam;

/**
* Updater thread. It will update the lock value in fixed interval.
*/
private Thread updater = null;

/**
* Is webcam locked (local, not cross-VM variable).
*/
private AtomicBoolean locked = new AtomicBoolean(false);

/**
* Lock file.
*/
private File lock = null;

/**
Expand Down Expand Up @@ -148,7 +159,7 @@ private void write(long value) {

// rewrite temporary file content to lock, try max 5 times

synchronized (MUTEX) {
synchronized (webcam) {
do {
try {
fos = new FileOutputStream(lock);
Expand Down Expand Up @@ -195,17 +206,21 @@ private void write(long value) {
}

private long read() {

DataInputStream dis = null;
try {
return (dis = new DataInputStream(new FileInputStream(lock))).readLong();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
throw new RuntimeException(e);

synchronized (webcam) {
try {
return (dis = new DataInputStream(new FileInputStream(lock))).readLong();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Expand Down

0 comments on commit d0de4ec

Please sign in to comment.