[SOLVED] Problem with threads and ReentrantLock

I have a problem with a reentrantLock, It never allows other threads to attain it.

The lock it self

private static Lock update = new ReentrantLock();

There is the code I’m using.
[spoiler]


@Override
    public void run(){
        while(Village.running || !scheduled.isEmpty()){               
            
            //Tasks thats need to done
            CoreTask task = getNextTask();
            if(task != null){
                long taskStart = System.nanoTime();
                task.start(); tps++;
                taskTime += System.nanoTime()-taskStart;
            }
            
            //Update the whole game
            long now = System.nanoTime();
            if(update.tryLock()){
                update.lock();
                try{
                    hasLocked = true;
                    delta += (now - lastTime) / (1000000000.0 / Village.targetUPS);
                    lastTime = now;
                    
                    Village.screenUpdate();
                    while(1.0 <= delta){
                        Village.gameUpdate();
                        delta--;
                    }
                    
                    System.out.println("Thread "+getThread().getName()+" is going to sleep.");
                }finally{
                    update.unlock();
                    System.out.println("Thread "+getThread().getName()+" is napping. update is unlocked: "+update.tryLock());
                    try{Thread.sleep(10000);}catch(Exception e){}
                }
            }else{
                System.out.println("Thread "+getThread().getName()+" filed to get the lock");
            }

            if(now-time > 1000000000){
                time = now;
                updateAllCoreInfo();
            }
            
            Thread.yield();
        }//While method ends.
    }//Run method ends.

[/spoiler]

Here is the output

if I remove line 34 to 36 (the else statement) I get this

Why don’t Thread-3 get the lock even when Thread-2 is asleep?

You are doing this:


if(update.tryLock()){
     update.lock();

That’s double locking it. You need to unlock it twice then. Proper usage of tryLock is this:


if (lock.tryLock()) {
  try {
    // do something
  } finally {
    lock.unlock();
  }
}

That should do it!

Thank so much, I thought .tryLock() only tested if it was locked or not

No problem! I’m glad you appreciate my help!

There you go. In case he didn’t get the hint.

oh sorry, I’m kind of new to this site so forgot about that. Sorry

Ha it’s not required or anything.

I suspect it’s secretly a competition and the winner gets a pony or something. So just in case it is, I like to remind people.