best way to figure out how long lock acquisition took.

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

best way to figure out how long lock acquisition took.

alarmnummer
What is the best way to figure out how much time a lock acquisition took?

I need to obtain multiple locks with a timout, and after each lock I need to check if there is enough time for the following lock.

so something like this:

boolean foo(long timeout, TimeUnit unit){
    long timeout, = unit.toUnit(timeOut,TimeOut.NANOS);
    long startTime = System.timeInNanos();

    if(!lock1.tryLock(timeout,TimeUnit.NANOS))
         return false;

    try{
           timeout- = System.timeInNanos()-startTime;         
           if(!lock2.tryLock(timeout,TimeUnit.NANOS))
                return false;

           try{
                  ...now do something.
           }finally{
                lock2.unlock();
           }
    }finally{
           lock1.unlock();
    }
}

Is this the recommended way to do it?


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: best way to figure out how long lock acquisition took.

tpeierls
Peter Veentjer wrote:
> I need to obtain multiple locks with a timout, and after each lock I
> need to check if there is enough time for the following lock.
>
> so something like this: [snip]

Yes. Here is a version that compiles:

   boolean foo(long timeout, TimeUnit unit) throws InterruptedException {
       timeout = unit.toNanos(timeout);
       long startTime = System.nanoTime();

       if (!lock1.tryLock(timeout, TimeUnit.NANOSECONDS))
           return false;
       try {
           timeout -= System.nanoTime() - startTime;
           if (!lock2.tryLock(timeout, TimeUnit.NANOSECONDS))
               return false;
           try {
               // do something with both locks held
               return true;
           } finally {
               lock2.unlock();
           }
       } finally {
           lock1.unlock();
       }
   }

--tim

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest