public
interface
Invokable
<
T
>
{
public
T
invoke
();
public
T
returnIfFail
();
}
import
java.util.concurrent.*
;
public
class
InvokeWrapper
<
T
>
{
private
final
static
ExecutorService
executor
=
Executors
.
newCachedThreadPool
();
private
Invokable
<
T
>
invokable
;
public
InvokeWrapper
(
Invokable
<
T
>
invokable
)
{
this
.
invokable
=
invokable
;
}
public
T
invokeWithTimeout
(
long
milliSec
)
{
T
result
=
null
;
Future
<
T
>
future
=
this
.
executor
.
submit
(
new
Callable
<
T
>()
{
@Override
public
T
call
()
throws
Exception
{
return
InvokeWrapper
.
this
.
invokable
.
invoke
();
}
});
try
{
result
=
future
.
get
(
milliSec
,
TimeUnit
.
MILLISECONDS
);
}
catch
(
Exception
e
)
{
result
=
this
.
invokable
.
returnIfFail
();
}
return
result
;
}
}