diff --git a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamProcessor.java b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamProcessor.java index ffd69ce1..65d66d09 100644 --- a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamProcessor.java +++ b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamProcessor.java @@ -17,6 +17,20 @@ public class WebcamProcessor { private static final Logger LOG = LoggerFactory.getLogger(WebcamProcessor.class); + /** + * Thread doing supersync processing. + * + * @author sarxos + */ + public static final class ProcessorThread extends Thread { + + private static final AtomicInteger N = new AtomicInteger(0); + + public ProcessorThread(Runnable r) { + super(r, String.format("atomic-processor-%d", N.incrementAndGet())); + } + } + /** * Thread factory for processor. * @@ -24,11 +38,9 @@ public class WebcamProcessor { */ private static final class ProcessorThreadFactory implements ThreadFactory { - private static final AtomicInteger N = new AtomicInteger(0); - @Override public Thread newThread(Runnable r) { - Thread t = new Thread(r, String.format("atomic-processor-%d", N.incrementAndGet())); + Thread t = new ProcessorThread(r); t.setUncaughtExceptionHandler(WebcamExceptionHandler.getInstance()); t.setDaemon(true); return t; diff --git a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamTask.java b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamTask.java index 299cadc2..9d725ae3 100644 --- a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamTask.java +++ b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamTask.java @@ -1,14 +1,16 @@ package com.github.sarxos.webcam; + + public abstract class WebcamTask { - private boolean sync = true; + private boolean doSync = true; private WebcamProcessor processor = null; private WebcamDevice device = null; private Throwable throwable = null; public WebcamTask(boolean threadSafe, WebcamDevice device) { - this.sync = !threadSafe; + this.doSync = !threadSafe; this.device = device; this.processor = WebcamProcessor.getInstance(); } @@ -31,13 +33,20 @@ public WebcamDevice getDevice() { * @throws InterruptedException when thread has been interrupted */ public void process() throws InterruptedException { - if (sync) { - if (processor == null) { - throw new RuntimeException("Driver should be synchronized, but processor is null"); - } - processor.process(this); - } else { + + boolean alreadyInSync = Thread.currentThread() instanceof WebcamProcessor.ProcessorThread; + + if (alreadyInSync) { handle(); + } else { + if (doSync) { + if (processor == null) { + throw new RuntimeException("Driver should be synchronized, but processor is null"); + } + processor.process(this); + } else { + handle(); + } } }