Skip to content

Instantly share code, notes, and snippets.

@riversun
Last active August 24, 2016 09:45
Show Gist options
  • Save riversun/27d88003258cbd520a487d4d25a27f17 to your computer and use it in GitHub Desktop.
Save riversun/27d88003258cbd520a487d4d25a27f17 to your computer and use it in GitHub Desktop.
[Java]Run some operations with timeout
/**
* Copyright 2006-2016 Tom Misawa(riversun.org@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.riversun;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Run some operations with timeout
*
* @author Tom Misawa (riversun.org@gmail.com)
*
*/
public class TimeoutExecutor {
public static void main(String[] args) {
TimeoutExecutor tex = new TimeoutExecutor();
TimeoutAction action = new TimeoutAction() {
@Override
public void run() {
while (!isTimeout()) {
System.out.println("Wait for timeout");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
//omittable
@Override
public void onTimeout() {
// call when timeout occurred
System.out.println("Timeout occured");
}
};
final long timeoutMillis = 5000;
tex.runActionWithTimeout(action, timeoutMillis);
}
/**
*
* class of Timeout Action
*
*/
public static abstract class TimeoutAction {
private boolean mIsTimeout = false;
/**
* Execute operation with timeout
*/
public abstract void run();
/**
* Call when timeout occurred
*/
public void onTimeout() {
}
/**
* Check if already timeout
*
* @return
*/
public boolean isTimeout() {
return mIsTimeout;
}
}
public void runActionWithTimeout(TimeoutAction action, long timeoutMillis) {
final Runnable r = new Runnable() {
@Override
public void run() {
action.run();
}
};
final ExecutorService ex = Executors.newSingleThreadExecutor();
try {
Future<?> future = ex.submit(r);
try {
future.get(timeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
// treat interruption as timeout
action.mIsTimeout = true;
action.onTimeout();
} catch (TimeoutException e) {
// When timeout occured
action.mIsTimeout = true;
action.onTimeout();
}
} finally {
ex.shutdownNow();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment