3

Does anyone know if it's possible to have an Ada-style select statement for threads in Java or if there is an equivalent way to do it?

Specifically I would like to be able to use structures:

select
  javaThread.someEntry();
else
  //do something else if call not accepted straight away
end select

or

select
  javaThread.someEntry();
or
  //delay before entry call expires
end select

Where someEntry() is a synchronized method that could take a bit of time to enter due to a lot of other threads wanting the lock as well.

Thanks!

4

1 回答 1

2

In Java, there are a number of ways of accomplishing this. One way is to use any of the Lock objects which has a tryLock(...) method which allows you to wait for the lock for a certain amount of time. It returns true if it was able to acquire the lock or false if it timed out. ReentrantLock may be a good choice here.

private final Lock lock = new ReentrantLock();
...

if (lock.tryLock(1L, TimeUnit.SECONDS)) {
   try {
      // we were able to lock
   } finally {
      // always unlock in a finally
      lock.unlock();
   }
} else {
   // trying to lock timed out without locking
}

After some discussion in comments, I now understand that you have existing synchronized methods that you'd like to wait for only for a certain amount of time. Unfortunately, there is no way to do this in Java with the synchronized keyword.

于 2012-10-01T00:36:19.470 回答