Q:

How to let other threads to continue on locking elements inside for loop java

Let's say I have below code
public class ContinueIfCannotLock implements Runnable
{

static List<LockingObject> lockObjects = new ArrayList();
@Override
   public void run()
   {
       for(LockingObject obj : lockObjects)
       {
           synchronized ( obj )
           {
            // do things here
           }
       }

   }

}

and the LockingObject is just and empty class. Also let's assume before these threads start we have 100 of objects in the LockingObject list.
So how can I let a thread to continue to next object in the list if it cannot acquire the lock to the current element. So that no thread (at least until all the objects are not locked by a thread) is waiting inside the loop.

A:

Try using Thread.holdsLock(Object obj),

Returns true if and only if the current thread holds the monitor lock on the specified object.
~Thread (Java Platform SE 8)~

static List<LockingObject> lockObjects = new ArrayList();
@Override
   public void run(){
       for(LockingObject obj : lockObjects){

           if(Thread.holdsLock(obj)){
               continue; //continue the loop if object is locked.
           }

           synchronized(obj){
               // do things here
           }
       }
   }
}

