Last active
January 4, 2016 16:19
-
-
Save dawnbreaks/8646544 to your computer and use it in GitHub Desktop.
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
public class BigLockCalculator extends CalculatorBase { | |
private interface Status { | |
int NotStarted =1; | |
int Starting =2; | |
int Started =3; | |
int Disposed =4; | |
} | |
private AtomicInteger _status = new AtomicInteger(Status.NotStarted); | |
private AtomicInteger _disposingFlag = new AtomicInteger(0); | |
private AtomicInteger _startingFlag = new AtomicInteger(0); | |
public override void Start() { | |
if(_status.get() != Status.NotStarted ) { | |
return; | |
} | |
if( _startingFlag.compareAndSwap(0,1)) { | |
try { | |
if(_status.compareAndSwap(Status.NotStarted, Status.Starting)) { | |
StartCore(); | |
if(!_status.compareAndSwap(Status.Starting, Status.Started)) { | |
if(_status.get() == Status.Disposed ) { | |
DisposeCore(); | |
return; | |
} | |
} | |
} | |
}finally { | |
_startingFlag.compareAndSwap(1,0); | |
} | |
} | |
} | |
public override void Dispose() { | |
if(_status.get() == Status.Disposed) { | |
return; | |
} | |
if( _disposingFlag.compareAndSwap(0,1)) { | |
try { | |
while(true) { | |
int currentStatus =_status.get(); | |
if(currentStatus == Status.Disposed) { | |
return; | |
} | |
if(currentStatus == Status.NotStarted && _status.compareAndSwap(currentStatus, Status.Disposed )) { | |
return; | |
}else if(currentStatus == Status.Starting && _status.compareAndSwap(currentStatus, Status.Disposed )){ | |
return; | |
}else if(currentStatus == Status.Started && _status.compareAndSwap(currentStatus, Status.Disposed )){ | |
DisposeCore(); | |
} | |
} | |
}finally { | |
_disposingFlag.compareAndSwap(1,0); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment