Commit good fix for race condition Daniel noted
[zxing.git] / android / src / com / google / zxing / client / android / DecodeThread.java
index c3d77de..75e5bad 100755 (executable)
@@ -27,6 +27,7 @@ import android.preference.PreferenceManager;
 
 import java.util.Hashtable;
 import java.util.Vector;
+import java.util.concurrent.CountDownLatch;
 
 /**
  * This thread does all the heavy lifting of decoding the images.
@@ -37,13 +38,20 @@ final class DecodeThread extends Thread {
 
   public static final String BARCODE_BITMAP = "barcode_bitmap";
 
-  private final Handler handler;
+  private final CaptureActivity activity;
+  private final Hashtable<DecodeHintType, Object> hints;
+  private Handler handler;
+  private final CountDownLatch handlerInitLatch;
 
   DecodeThread(CaptureActivity activity,
                Vector<BarcodeFormat> decodeFormats,
                String characterSet,
                ResultPointCallback resultPointCallback) {
-    Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
+
+    this.activity = activity;
+    handlerInitLatch = new CountDownLatch(1);
+
+    hints = new Hashtable<DecodeHintType, Object>(3);
 
     // The prefs can't change while the thread is running, so pick them up once here.
     if (decodeFormats == null || decodeFormats.isEmpty()) {
@@ -66,17 +74,22 @@ final class DecodeThread extends Thread {
     }
 
     hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
-
-    this.handler = new DecodeHandler(activity, hints);
   }
 
   Handler getHandler() {
+    try {
+      handlerInitLatch.await();
+    } catch (InterruptedException ie) {
+      // continue?
+    }
     return handler;
   }
 
   @Override
   public void run() {
     Looper.prepare();
+    handler = new DecodeHandler(activity, hints);
+    handlerInitLatch.countDown();
     Looper.loop();
   }