/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package doublex.lib.locks;

import java.util.AbstractMap;
import java.util.LinkedHashMap;

/**
 *
 * @author DoubleX
 * @param <K>
 */
public final class Locks<K> implements ILocks<K> {

    private final ILockable<K> NULL_LOCK = new NullLock<>();

    private final AbstractMap<String, ILockable<K>> mLocks = 
            new LinkedHashMap<>();

    @Override
    public final ILockable<K> lock(final String key) {
        return mLocks.containsKey(key) ? mLocks.get(key) : NULL_LOCK;
    }

    @Override
    public final boolean isLocked() {
        return mLocks.values().stream().anyMatch((lock) -> (lock.isLocked()));
    }

    @Override
    public final void tryPutLock(final String key, final ILockable<K> lock) {
        if (canPutLock(key, lock)) putLock(key, lock);
    }

    @Override
    public final ILockable<K> triedTakenLock(final String key) {
        return (canTakeLock(key)) ? takenLock(key) : NULL_LOCK;
    }

    private boolean canPutLock(final String key, final ILockable<K> lock) {
        return !mLocks.containsKey(key) && !lock.isLocked();
    }

    private void putLock(final String key, final ILockable<K> lock) {
        mLocks.put(key, lock);
    }

    private boolean canTakeLock(final String key) {
        return mLocks.containsKey(key) && !mLocks.get(key).isLocked();
    }

    private ILockable<K> takenLock(final String key) {
        final ILockable<K> lock = lock(key);
        mLocks.remove(key);
        return lock;
    }

}

@@ -239,40 +239,8 @@
 Map;
-%0Aimport java.util.LinkedHashMap;
 %0A%0A/*
@@ -457,46 +457,106 @@
 ocks
- = %0A            new LinkedHashMap%3C%3E();
+;%0A%0A    public Locks(final AbstractMap%3CString, ILockable%3CK%3E%3E locks) %7B%0A        mLocks = locks;%0A    %7D
 %0A%0A  
@@ -570,38 +570,32 @@
 ride%0A    public 
-final 
 ILockable%3CK%3E loc
@@ -718,22 +718,16 @@
  public 
-final 
 boolean 
@@ -850,22 +850,16 @@
  public 
-final 
 void try
@@ -945,16 +945,30 @@
 , lock))
+ %7B%0A           
  putLock
@@ -972,32 +972,42 @@
 ock(key, lock);%0A
+        %7D%0A
     %7D%0A%0A    @Over
@@ -1022,22 +1022,16 @@
  public 
-final 
 ILockabl

Update Locks.java