From d0de4ecd755723de04eaae46eeaac048c7abc7fc Mon Sep 17 00:00:00 2001 From: Bartosz Firyn Date: Sat, 3 Aug 2013 10:26:09 +0200 Subject: [PATCH] Synchronize lock read method, refs #131 --- .../com/github/sarxos/webcam/WebcamLock.java | 43 +++++++++++++------ 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamLock.java b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamLock.java index 8ce113c0..d231af45 100644 --- a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamLock.java +++ b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamLock.java @@ -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) */ @@ -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). */ @@ -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; /** @@ -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); @@ -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); + } } } }