For concurrency we used java.util.concurrent that allows to start calls simultaneously. Number of calls depends on available processors.
Countdown latch guarantees that processes would be started simultaneously.
import com.google.gson.Gson;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import static io.restassured.RestAssured.UNDEFINED_PORT;
import static io.restassured.RestAssured.given;
import static org.apache.commons.lang3.time.DateUtils.addSeconds;
import static org.junit.Assert.assertTrue;
/**
* Created by Yulia_Atlasova on 9/25/2016.
*/
public class Example {
@Test
public void canCreateLibrariesSimultaneously() throws ExecutionException, InterruptedException {
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(threads);
CountDownLatch latch = new CountDownLatch(threads);
List<Future<Library>> futures = new ArrayList<>(threads);
List<Library> libraries = new ArrayList<>(threads);
Gson gson = new Gson();
for (int i = 0; i < threads; i++) {
Future<Library> future = service.submit(() -> {
latch.countDown();
latch.await();
return gson.fromJson(given()
.port(UNDEFINED_PORT)
.urlEncodingEnabled(false)
.queryParam("RequestId", new Date().getTime())
.post().asString(), Library.class);
});
futures.add(future);
}
for (Future<Library> future : futures) {
libraries.add(future.get());
}
Date now = new Date();
service.shutdown();
for (Library library : libraries) {
Date created = library.getServiceData().getCreatedTimestamp();
assertTrue("Created timestamp should be within last 2 seconds, but it is: " + created,
created.after(addSeconds(now, -2)) && created.before(now));
}
}
}
On Sunday, 28 August 2016 23:16:37 UTC+3, vinod komeershetty wrote: