views:

76

answers:

3

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;
    }
}
+4  A: 
while(!tryToLock())
    {
        Thread.sleep(1000);
    }

Terrible idea.

Use a Lock implementation from java.util.concurrent.

Or just a synchronized block.

Thilo
thank you for the link
fredcrs
+3  A: 

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.

edA-qa mort-ora-y
+3  A: 

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();
    ...
}
Jonathan