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!
In Java, there are a number of ways of accomplishing this. One way is to use any of the
Lockobjects which has atryLock(...)method which allows you to wait for the lock for a certain amount of time. It returnstrueif it was able to acquire the lock orfalseif it timed out.ReentrantLockmay be a good choice here.After some discussion in comments, I now understand that you have existing
synchronizedmethods 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 thesynchronizedkeyword.