[Android] Fix a race condition when initializing libvlc

Martin Storsjö git at videolan.org
Sat Jul 7 21:54:04 CEST 2012


android | branch: master | Martin Storsjö <martin at martin.st> | Sat Jul  7 22:52:14 2012 +0300| [9357890f4e1756a0475852dc8651287039de3295] | committer: Martin Storsjö

Fix a race condition when initializing libvlc

getInstance() is called from multiple threads at startup
(e.g. via MediaLibrary.loadMediaItems), and if one of them
has started initializing libvlc but not yet finished doing so,
other threads could go ahead and use the not yet fully initialized
libvlc.

> http://git.videolan.org/gitweb.cgi/android.git/?a=commit;h=9357890f4e1756a0475852dc8651287039de3295
---

 vlc-android/src/org/videolan/vlc/LibVLC.java |   14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/vlc-android/src/org/videolan/vlc/LibVLC.java b/vlc-android/src/org/videolan/vlc/LibVLC.java
index b6d0278..af674c1 100644
--- a/vlc-android/src/org/videolan/vlc/LibVLC.java
+++ b/vlc-android/src/org/videolan/vlc/LibVLC.java
@@ -92,17 +92,21 @@ public class LibVLC {
      * @throws LibVlcException
      */
     public static LibVLC getInstance() throws LibVlcException {
-        if (sInstance == null) {
-            /* First call */
-            sInstance = new LibVLC();
-            sInstance.init();
+        synchronized (LibVLC.class) {
+            if (sInstance == null) {
+                /* First call */
+                sInstance = new LibVLC();
+                sInstance.init();
+            }
         }
 
         return sInstance;
     }
 
     public static LibVLC getExistingInstance() {
-        return sInstance;
+        synchronized (LibVLC.class) {
+            return sInstance;
+        }
     }
 
     /**



More information about the Android mailing list