Igman
Igman

Reputation: 277

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.

Upvotes: 5

Views: 4058

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533510

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

Upvotes: 3

corsiKa
corsiKa

Reputation: 82579

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.

Upvotes: 3

mikera
mikera

Reputation: 106351

How about just

Thread.sleep(10 + new Random().nextInt(20)); // waits between 10 - 30 ms.

i.e. in the code that responds to the JMS call you just use this to simulate a random latency delay.

Upvotes: 2

zengr
zengr

Reputation: 38899

You can schedule jobs using Quartz, does that solve the purpose?

Upvotes: 0

Related Questions