package org.ccci.gto.android.common.util;

import android.os.Looper;

import java.util.Map;

public final class ThreadUtils {
    private ThreadUtils() {
    }

    public static void assertNotOnUiThread() {
        if (isUiThread()) {
            throw new RuntimeException("unsupported method on UI thread");
        }
    }

    public static void assertOnUiThread() {
        if (!isUiThread()) {
            throw new RuntimeException("method requires UI thread");
        }
    }

    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
    public static <K> Object getLock(final Map<K, Object> locks, final K key) {
        synchronized (locks) {
            if (!locks.containsKey(key)) {
                locks.put(key, new Object());
            }
            return locks.get(key);
        }
    }

    public static boolean isUiThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
}

@@ -61,16 +61,151 @@
 .Looper;
+%0Aimport android.support.annotation.NonNull;%0Aimport android.support.annotation.Nullable;%0Aimport android.support.v4.util.LongSparseArray;
 %0A%0Aimport
@@ -281,21 +281,16 @@
 tils() %7B
-%0A    
 %7D%0A%0A    p
@@ -606,24 +606,37 @@
    %7D%0A    %7D%0A%0A
+    @NonNull%0A
     @Suppres
@@ -733,16 +733,25 @@
 getLock(
+@NonNull 
 final Ma
@@ -769,16 +769,26 @@
 %3E locks,
+ @Nullable
  final K
@@ -842,35 +842,411 @@
     
-if (!locks.containsKey(key)
+Object lock = locks.get(key);%0A            if (lock == null) %7B%0A                lock = new Object();%0A                locks.put(key, lock);%0A            %7D%0A            return lock;%0A        %7D%0A    %7D%0A%0A    @NonNull%0A    @SuppressWarnings(%22SynchronizationOnLocalVariableOrMethodParameter%22)%0A    public static Object getLock(@NonNull final LongSparseArray%3CObject%3E locks, final long key) %7B%0A        synchronized (locks
 ) %7B%0A
@@ -1261,39 +1261,142 @@
     
-   
+Object lock =
  locks.
-pu
+ge
 t(key
-, new Object()
+);%0A            if (lock == null) %7B%0A                lock = new Object();%0A                locks.put(key, lock
 );%0A 
@@ -1427,34 +1427,24 @@
  return lock
-s.get(key)
 ;%0A        %7D%0A

improve performance of getLock and add LongSparseArray variety