Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate latency in Java

I am developing a simple test framework in Java that needs to simulate weblogic deployments by responding to JMS calls. One of the the test configuration options is a delay to simulate latency. I was wondering if anyone has any good ideas on how to do this. I was jsut going to create a TimerTask to handle it, is there a better way? Thanks.

like image 279
Igman Avatar asked Feb 27 '23 18:02

Igman


2 Answers

You can create a ScheduledExecutorService to perform what you would do after a delay.

private final ScheduledExecutorService executor =
    Executors.newSingleThreadScheduledExecutor();


// is main loop, waits between 10 - 30 ms.  
executor.schedule(new Runnable() { public void run() {
   // my delayed task
}}, 10 + new Random().nextInt(20), TimeUnit.MILLI_SECOND); 

EDIT: You can use the Concurrency Backport for JDK 1.4. It works for JDK 1.2 to JDK 6

like image 158
Peter Lawrey Avatar answered Mar 01 '23 09:03

Peter Lawrey


Create an Object that mocks the server. When it "receives" your input, have it spawn a new thread to "handle the connection" like a real server would. That spawned thread can Thread.sleep() to its heart's content to simulate both send and receive lag, as well as allow you to mock some server-state properties that might be useful during testing.

like image 39
corsiKa Avatar answered Mar 01 '23 09:03

corsiKa