@@ -68,7 +68,9 @@ public void run() {
68
68
69
69
private ShutdownHook hook = null ;
70
70
private WebcamDevice device = null ;
71
- private boolean open = false ;
71
+
72
+ private volatile boolean open = false ;
73
+ private volatile boolean disposed = false ;
72
74
73
75
/**
74
76
* Webcam class.
@@ -264,12 +266,19 @@ public void setViewSize(Dimension size) {
264
266
*
265
267
* @return Captured image
266
268
*/
267
- public synchronized BufferedImage getImage () {
268
- if (!open ) {
269
- LOG .debug ("Try to get image on closed webcam, opening it automatically" );
270
- open ();
269
+ public BufferedImage getImage () {
270
+
271
+ if (disposed ) {
272
+ return null ;
273
+ }
274
+
275
+ synchronized (this ) {
276
+ if (!open ) {
277
+ LOG .debug ("Try to get image on closed webcam, opening it automatically" );
278
+ open ();
279
+ }
280
+ return device .getImage ();
271
281
}
272
- return device .getImage ();
273
282
}
274
283
275
284
/**
@@ -290,15 +299,13 @@ public static List<Webcam> getWebcams() {
290
299
driver = new WebcamDefaultDriver ();
291
300
}
292
301
293
- List <WebcamDevice > devices = driver .getDevices ();
302
+ for (WebcamDevice device : driver .getDevices ()) {
303
+ webcams .add (new Webcam (device ));
304
+ }
294
305
295
306
if (deallocOnTermSignal ) {
296
307
LOG .warn ("Automated deallocation on TERM signal is enabled!" );
297
- WebcamDeallocator .store (devices .toArray (new WebcamDevice [devices .size ()]));
298
- }
299
-
300
- for (WebcamDevice device : devices ) {
301
- webcams .add (new Webcam (device ));
308
+ WebcamDeallocator .store (webcams .toArray (new Webcam [webcams .size ()]));
302
309
}
303
310
304
311
if (LOG .isInfoEnabled ()) {
@@ -471,8 +478,23 @@ public WebcamDevice getDevice() {
471
478
* used any more and reinstantiation is required.
472
479
*/
473
480
protected void dispose () {
474
- device .close ();
475
- device .dispose ();
481
+
482
+ open = false ;
483
+ disposed = true ;
484
+
485
+ WebcamEvent we = new WebcamEvent (this );
486
+ for (WebcamListener l : listeners ) {
487
+ try {
488
+ l .webcamDisposed (we );
489
+ } catch (Exception e ) {
490
+ LOG .error (String .format ("Notify webcam disposed, exception when calling %s listener" , l .getClass ()), e );
491
+ }
492
+ }
493
+
494
+ synchronized (this ) {
495
+ device .close ();
496
+ device .dispose ();
497
+ }
476
498
}
477
499
478
500
/**
0 commit comments