Java tutorial
//package com.java2s; //License from project: Apache License import android.util.Log; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; public class Main { private static final String TAG = "ChatHelper"; private static ConcurrentHashMap<String, Semaphore> semaphoreMap = new ConcurrentHashMap<>(); /** * Locks a semaphore for handling multi threading with insert/delete/update methods. * * @param key key for inserting the locked semaphore in a hashmap. * @return the locked semaphore. */ public static boolean lockChat(String key) { Semaphore semaphore = new Semaphore(1); Semaphore oldSemaphore = semaphoreMap.putIfAbsent(key, semaphore); if (oldSemaphore != null) { semaphore = oldSemaphore; } //semaphore.tryAcquire(30, TimeUnit.SECONDS); try { semaphore.acquire(); return true; } catch (InterruptedException ignored) { Log.w(TAG, "Could not acquire chat: " + key); return false; } } }