Skip to content

Instantly share code, notes, and snippets.

@dawnbreaks
Last active January 4, 2016 16:19
Show Gist options
  • Save dawnbreaks/8646544 to your computer and use it in GitHub Desktop.
Save dawnbreaks/8646544 to your computer and use it in GitHub Desktop.
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