Advertisement
Kostiggig

Dispatchers.IO vs Dispatchers.Default

Apr 30th, 2023 (edited)
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.54 KB | None | 0 0
  1. package coroutines;
  2.  
  3. import java.io.IOException;
  4. import java.net.URI;
  5. import java.net.http.HttpClient;
  6. import java.net.http.HttpRequest;
  7. import java.net.http.HttpResponse;
  8. import java.util.*;
  9. import java.util.concurrent.*;
  10. import java.util.concurrent.atomic.AtomicLong;
  11.  
  12. public class Client {
  13.  
  14.     private static final int NUMBER_OF_TASKS = 1000;
  15.  
  16.     // Need to generate random delay
  17.     private static final Random random = new Random();
  18.     private static final AtomicLong counter = new AtomicLong();
  19.  
  20.     // Key is a ThreadName, Value is a list of tasks' id executed by Thread with ThreadName
  21.     private static final Map<String, List<Long>> map = new ConcurrentHashMap<>();
  22.  
  23.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  24.         int cpusCount = Runtime.getRuntime().availableProcessors();
  25.         ExecutorService executor = Executors.newFixedThreadPool(cpusCount);
  26.         //Uncomment this to test Executors.newCachedThreadPool();
  27.         // executor = Executors.newCachedThreadPool();
  28.  
  29.         HttpClient client = HttpClient.newBuilder().build();
  30.  
  31.         long start = System.currentTimeMillis();
  32.         for (int i = 0; i < NUMBER_OF_TASKS; i++) {
  33.  
  34.             long taskId = i + 1;
  35.             HttpRequest request = HttpRequest.newBuilder().uri(
  36.                     URI.create("https://jsonplaceholder.typicode.com/posts")
  37.             ).build();
  38.  
  39.             randomSleep(0,30);
  40.             Runnable task = getRunnable(executor, request, client, taskId);
  41.             executor.execute(task);
  42.         }
  43.  
  44.         // Need it to reach this line only after executing NUMBER_OF_TASKS Runnables
  45.         while(counter.get() != NUMBER_OF_TASKS) {}
  46.  
  47.         long end = System.currentTimeMillis();
  48.  
  49.         map.forEach((key, value) -> {
  50.             System.out.println(key + " - " + value);
  51.         });
  52.  
  53.         System.out.println("Count of used threads " + map.size());
  54.         System.out.println("Time has spent " + (end - start) + " ms");
  55.     }
  56.  
  57.     private static Runnable getRunnable(ExecutorService executor, HttpRequest request, HttpClient client, long taskId) {
  58.         return () -> {
  59.             try {
  60.                 System.out.println("Thread " + Thread.currentThread().getName() + " executes " + taskId + " task");
  61.  
  62.                 saveInfoAboutWhichThreadExecutesTask(taskId);
  63.  
  64.                 randomSleep(100, 300);
  65.                
  66.                 counter.getAndIncrement();
  67.  
  68.                 // ignore the result from server
  69.                 client.send(request, HttpResponse.BodyHandlers.ofString()).body();
  70.             } catch (IOException | InterruptedException e) {
  71.                 throw new RuntimeException(e);
  72.             }
  73.         };
  74.     }
  75.  
  76.     private static void randomSleep(int from, int until) {
  77.         try {
  78.             Thread.sleep(from + random.nextInt(until));
  79.         } catch (InterruptedException e) {
  80.             throw new RuntimeException(e);
  81.         }
  82.     }
  83.  
  84.     private static void saveInfoAboutWhichThreadExecutesTask(long taskId) {
  85.         String key = Thread.currentThread().getName();
  86.         if(map.get(key) == null) {
  87.  
  88.             // List should be syncrhonized to avoid java.lang.UnsupportedOperationException
  89.             map.put(key, Collections.synchronizedList(new ArrayList<>()));
  90.         }
  91.  
  92.         List<Long> taskIdsByThreadName = map.get(key);
  93.         taskIdsByThreadName.add(taskId);
  94.  
  95.         // should be atomically to avoid race condition check-then-act problem
  96.         map.put(Thread.currentThread().getName(), taskIdsByThreadName);
  97.     }
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement