Reputation: 3621
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;
}
}
Upvotes: 0
Views: 127
Reputation: 13624
Your tryToUnlock()
method is incorrect, but otherwise it would technically work.
Most Java programmers would do something more like this, though:
synchronized (object) {
object.doSomething();
object.doSomethingElse();
...
}
Upvotes: 3
Reputation: 31911
Based on your intent it'd be far easier to just do this (since you can use any object as a mutex in Java):
synchronized( object ) {
object.doSomething();
object.doAnotherThing();
object.doAnotherThingYet();
}
If you need finer control, and a tryLock in particular, then look at the "Lock" interface and the classes that implement it.
Upvotes: 3
Reputation: 262724
while(!tryToLock())
{
Thread.sleep(1000);
}
Terrible idea.
Use a Lock implementation from java.util.concurrent.
Or just a synchronized
block.
Upvotes: 4