Today i'm gonna share one of many possible ways to acquire a lock with the intent of synchronize transitions or whatever task you may have. I use it to synchronize complex animation transition sequences in Android.
import java.util.HashSet; import java.util.Set; /** * Use this class to synchronize transitions, animations or whatever you want. * It is designed to acquire and release a synchronized lock state, coordinating * the access of it in a multi thread environment. * * @author Ricardo Ferreira 04/11/2013 */ public class StateLock { private final static StateLock INSTANCE = new StateLock(); private SetlockSet = new HashSet (); private boolean lock = false; private StateLock() { // singleton } /** Synchronized because the lock state should be acquired and released in a controlled way */ public synchronized static StateLock getInstance() { return StateLock.INSTANCE; } public synchronized boolean isStateLocked() { return lock; } public synchronized boolean hasStateAlreadyLocked(String stateSimpleClassName) { return lockSet.contains(stateSimpleClassName); } /** Returns true if the state lock was acquired by the given class, false otherwise */ public synchronized boolean acquireLockState(String stateSimpleClassName) { boolean operationResult = false; if (lockSet.isEmpty()) { lockSet.add(stateSimpleClassName); lock = true; operationResult = true; } return operationResult; } /** Returns true if the lock was released or no state was locked, false otherwise */ public synchronized boolean releaseLockState(String stateSimpleClassName) { boolean operationResult = false; if (lockSet.contains(stateSimpleClassName)) { lockSet.clear(); lock = false; operationResult = true; } else if (lockSet.isEmpty()) { lock = false; operationResult = true; } return operationResult; } protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👇Be sure to read, it will change your life!Show your work by Austin Kleon: https://amzn.to/34NVmwxThis book is a must read - it will put you in another level! (Expert)Agile Software Development, Principles, Patterns, and Practices: https://amzn.to/30WQSm2Write cleaner code and stand out!Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSvThis book is very practical, straightforward and to the point! Worth every penny!Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gpNeedless to say, these are top right?Apple AirPods Pro: https://amzn.to/2GOICxy😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👆