So the thing is, I want to be able to do this with my class.
object.lockAccess();
object.doSomething();
object.doAnotherThing();
object.doAnotherThingYet();
object.unlockAccess();
So the other thread will not be able to access my class methods while locked.
Here is the implementation I did, I was wondering if someone got a better idea, or if it may fail.
private boolean locked = false;
public void lockAccess() throws Exception
{
while(!tryToLock())
{
Thread.sleep(1000);
}
}
public void unlockAccess() throws Exception
{
while(!tryToUnlock())
{
Thread.sleep(1000);
}
}
private synchronized boolean tryToLock()
{
if(locked)
return false;
else
{
locked = true;
return true;
}
}
private synchronized boolean tryToUnlock()
{
if(locked)
return false;
else
{
locked = false;
return true;
}
}
Terrible idea.
Use a Lock implementation from java.util.concurrent.
Or just a
synchronizedblock.