Follow treslines by email clicking Here!

Monday, November 4, 2013

How to lock state to synchonize transitions java android

Hi there!
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 Set lockSet = 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();
 }

}

No comments:

Post a Comment