TimeoutDispatcherTest.java
/***************************************************************************
Copyright 2015 Emily Estes
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 net.metanotion.util;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public final class TimeoutDispatcherTest {
private static final class Test implements Message<Long> {
@Override public Object call(final Long timeout) {
try {
Thread.sleep(timeout);
} catch (final InterruptedException ie) { throw new RuntimeException(ie); }
return this;
}
@Override public Class<Long> receiverType() { return Long.class; }
}
private static final class Disp implements Dispatcher<Long, Object> {
@Override public Message<Long> dispatch(final Object data) { return new Test(); }
}
private static final long TIMEOUT = 5000L;
public static void main(final String[] args) throws Exception {
final ExecutorService es = Executors.newCachedThreadPool();
try {
final Disp d = new Disp();
final TimeoutDispatcherMixin<Long, Object> disp = new TimeoutDispatcherMixin<>(es, TimeUnit.MILLISECONDS, TIMEOUT, d);
final Message<Long> m1 = disp.dispatch(null);
if(m1.receiverType()!=Long.class) {
throw new AssertionError("Expected Receiver to be Long");
}
m1.call(1000L);
m1.call(2000L);
try {
m1.call(6000L);
throw new AssertionError("This call should timeout and throw an Exception.");
} catch (final RuntimeException ex) {
// Expected.
}
final Message<Long> m2 = disp.dispatch(null);
try {
m2.call(10000L);
throw new AssertionError("This call should timeout and throw an Exception.");
} catch (final RuntimeException ex) {
// Expected.
}
m2.call(1000L);
} finally {
es.shutdownNow();
}
}
}