Created
April 7, 2013 02:17
-
-
Save jbowens/5328591 to your computer and use it in GitHub Desktop.
A TTAS lock implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple lock interface. | |
*/ | |
public interface Lock { | |
/** | |
* Acquires the lock. | |
*/ | |
void lock(); | |
/** | |
* Acquires the lock if avilable when invoked. If the | |
* lock is not available, this method will not block. | |
*/ | |
boolean tryLock(); | |
/** | |
* Releases the lock. | |
*/ | |
void unlock(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.atomic.AtomicBoolean; | |
/** | |
* A simple test-test-and-set lock. | |
* | |
* @author jbowens | |
* @since April 2013 | |
*/ | |
public class TestTestAndSetLock implements Lock { | |
/** | |
* Whether or not the lock is locked. | |
*/ | |
protected AtomicBoolean m_locked; | |
/** | |
* Constructs a new TTAS lock. | |
*/ | |
public TestTestAndSetLock() { | |
m_locked = new AtomicBoolean(false); | |
} | |
/** | |
* Locks the lock. | |
*/ | |
public void lock() { | |
boolean acquired = false; | |
while(!acquired) { | |
/* First test the lock without invalidating | |
any cache lines. */ | |
if(!m_locked.get()) { | |
/* Attempt to lock the lock with an atomic CAS. */ | |
acquired = m_locked.compareAndSet(false, true); | |
} | |
} | |
} | |
/** | |
* Locks the lock if available. This will not | |
* block. | |
*/ | |
public boolean tryLock() { | |
if(m_locked.get()) { | |
return false; | |
} | |
return m_locked.compareAndSet(false, true); | |
} | |
/** | |
* Unlocks the lock. This will not block. | |
*/ | |
public void unlock() { | |
m_locked.set(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment