Wednesday, February 4, 2009

Light lock

Request for comments

The Light lock is a reentrant CAS lock.



public class Light
extends java.util.concurrent.atomic.AtomicBoolean
{

private volatile java.lang.Thread writer;

private int enterRead, enterWrite;


public Light(){
super();
this.set(true);
}


public final void lockReadEnter(){
if (this.compareAndSet(true,true)){
synchronized(this){
this.enterRead += 1;
}
return;
}
else {
java.lang.Thread T = java.lang.Thread.currentThread();
if (T == this.writer){
synchronized(this){
this.enterRead += 1;
}
return;
}
else {
try {
while (true){
synchronized(this){
if (this.compareAndSet(true,true)){
this.enterRead += 1;
return ;
}
else
this.wait();
}
}
}
catch (java.lang.InterruptedException exc){
throw new java.lang.RuntimeException(exc);
}
}
}
}
public final synchronized void lockReadExit(){
this.enterRead -= 1;
this.notify();
}
public final boolean lockWriteEnterTry(){
java.lang.Thread T = java.lang.Thread.currentThread();
if (T == this.writer){
synchronized(this){
this.enterWrite += 1;
}
return true;
}
else if (this.compareAndSet(true,false)){
/*
* exclude others, and then wait for readers to exit
*/
try {
synchronized(this){
while (true){
if (0 == this.enterRead){
this.writer = T;
this.enterWrite += 1;
return true;
}
else {
this.wait();
}
}
}
}
catch (java.lang.InterruptedException exc){
throw new java.lang.RuntimeException(exc);
}
}
else
return false;
}
public final void lockWriteEnter(){
if (this.lockWriteEnterTry())
return;
else {
try {
while (true){
synchronized(this){
if (this.lockWriteEnterTry())
return;
else
this.wait();
}
}
}
catch (java.lang.InterruptedException exc){
throw new java.lang.RuntimeException(exc);
}
}
}
public final synchronized void lockWriteExit(){
java.lang.Thread W = this.writer;
java.lang.Thread T = java.lang.Thread.currentThread();
if (T == W){
this.enterWrite -= 1;
if (0 == this.enterWrite){
if (this.compareAndSet(false,true)){
this.writer = null;
this.notify();
}
else
throw new java.lang.IllegalStateException();
}
else
return;
}
else if (null == W)
throw new java.lang.IllegalStateException();
else
throw new java.lang.IllegalStateException();
}
public final boolean isWriteLocked(){
return (!this.get());
}
public final boolean isNotWriteLocked(){
return this.get();
}
public final boolean isWriteLocker(){
java.lang.Thread T = java.lang.Thread.currentThread();
return (T == this.writer);
}
public final boolean isNotWriteLocker(){
java.lang.Thread T = java.lang.Thread.currentThread();
return (T != this.writer);
}
}

1 comment:

John Douglas Pritchard said...
This comment has been removed by the author.