Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package coroutines;
- import java.io.IOException;
- import java.net.URI;
- import java.net.http.HttpClient;
- import java.net.http.HttpRequest;
- import java.net.http.HttpResponse;
- import java.util.*;
- import java.util.concurrent.*;
- import java.util.concurrent.atomic.AtomicLong;
- public class Client {
- private static final int NUMBER_OF_TASKS = 1000;
- // Need to generate random delay
- private static final Random random = new Random();
- private static final AtomicLong counter = new AtomicLong();
- // Key is a ThreadName, Value is a list of tasks' id executed by Thread with ThreadName
- private static final Map<String, List<Long>> map = new ConcurrentHashMap<>();
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- int cpusCount = Runtime.getRuntime().availableProcessors();
- ExecutorService executor = Executors.newFixedThreadPool(cpusCount);
- //Uncomment this to test Executors.newCachedThreadPool();
- // executor = Executors.newCachedThreadPool();
- HttpClient client = HttpClient.newBuilder().build();
- long start = System.currentTimeMillis();
- for (int i = 0; i < NUMBER_OF_TASKS; i++) {
- long taskId = i + 1;
- HttpRequest request = HttpRequest.newBuilder().uri(
- URI.create("https://jsonplaceholder.typicode.com/posts")
- ).build();
- randomSleep(0,30);
- Runnable task = getRunnable(executor, request, client, taskId);
- executor.execute(task);
- }
- // Need it to reach this line only after executing NUMBER_OF_TASKS Runnables
- while(counter.get() != NUMBER_OF_TASKS) {}
- long end = System.currentTimeMillis();
- map.forEach((key, value) -> {
- System.out.println(key + " - " + value);
- });
- System.out.println("Count of used threads " + map.size());
- System.out.println("Time has spent " + (end - start) + " ms");
- }
- private static Runnable getRunnable(ExecutorService executor, HttpRequest request, HttpClient client, long taskId) {
- return () -> {
- try {
- System.out.println("Thread " + Thread.currentThread().getName() + " executes " + taskId + " task");
- saveInfoAboutWhichThreadExecutesTask(taskId);
- randomSleep(100, 300);
- counter.getAndIncrement();
- // ignore the result from server
- client.send(request, HttpResponse.BodyHandlers.ofString()).body();
- } catch (IOException | InterruptedException e) {
- throw new RuntimeException(e);
- }
- };
- }
- private static void randomSleep(int from, int until) {
- try {
- Thread.sleep(from + random.nextInt(until));
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- private static void saveInfoAboutWhichThreadExecutesTask(long taskId) {
- String key = Thread.currentThread().getName();
- if(map.get(key) == null) {
- // List should be syncrhonized to avoid java.lang.UnsupportedOperationException
- map.put(key, Collections.synchronizedList(new ArrayList<>()));
- }
- List<Long> taskIdsByThreadName = map.get(key);
- taskIdsByThreadName.add(taskId);
- // should be atomically to avoid race condition check-then-act problem
- map.put(Thread.currentThread().getName(), taskIdsByThreadName);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement