
//spin lock -> busy waiting

public class SpinLockProblem extends MutexProblem {

	//shared variablvolatilee
	private volatile boolean lock = false;
	
	@Override
	AbstractProcess createProcess(int type) {
		//create and return an AbstractProcess
		return new AbstractProcess(type) {

			@Override
			protected boolean entrySection() {
				//wait as long as the lock is true
				//while(lock);
				//lock it
				//lock = true;
				
				//test and set the lock
				while(testAndSetLock());
				
				//go into the critical region
				return true;
			}

			@Override
			protected void exitSection() {
				//lock = false;
				resetLock();
			}
			
		};
	}

	@Override
	public String toString() {
		return "spin lock = " + lock;
	}
	
	//simulate the test and set instruction
	public synchronized boolean testAndSetLock() {
		//return the old lock value
		boolean temp = lock;
		//set the lock to true
		lock = true;
		return temp;
	}
	
	public synchronized void resetLock() {
		lock = false;
	}
	

}
