|
| 1 | +# Cheat Sheet |
| 2 | +## Concurrent Data Structures |
| 3 | + |
| 4 | +### 1. ConcurrentHashMap |
| 5 | +- **Usage**: A thread-safe variant of `HashMap`. |
| 6 | +- **Example**: |
| 7 | + ``` |
| 8 | + ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); |
| 9 | + map.put("key", 1); |
| 10 | + int value = map.get("key"); |
| 11 | + |
| 12 | +### 2. CopyOnWriteArrayList |
| 13 | +- **Usage**: A thread-safe variant of ArrayList for read-mostly scenarios. |
| 14 | +- **Example**: |
| 15 | +``` |
| 16 | +List<String> list = new CopyOnWriteArrayList<>(); |
| 17 | +list.add("element"); |
| 18 | +for (String s : list) { |
| 19 | + System.out.println(s); |
| 20 | +} |
| 21 | +``` |
| 22 | +
|
| 23 | +### 3. BlockingQueue |
| 24 | +- **Usage**: Thread-safe queues that block on operations when necessary. |
| 25 | +
|
| 26 | +Types: |
| 27 | +ArrayBlockingQueue |
| 28 | +LinkedBlockingQueue |
| 29 | +PriorityBlockingQueue |
| 30 | +- **Example**: |
| 31 | +``` |
| 32 | +BlockingQueue<String> queue = new ArrayBlockingQueue<>(10); |
| 33 | +queue.put("element"); |
| 34 | +String element = queue.take(); |
| 35 | +``` |
| 36 | +
|
| 37 | +### 4. ConcurrentSkipListMap |
| 38 | +Usage: A thread-safe variant of TreeMap for scalable sorted maps. |
| 39 | +- **Example**: |
| 40 | +
|
| 41 | +``` |
| 42 | +ConcurrentNavigableMap<String, Integer> map = new ConcurrentSkipListMap<>(); |
| 43 | +map.put("key", 1); |
| 44 | +int value = map.get("key"); |
| 45 | +``` |
| 46 | +
|
| 47 | +### 5. DelayQueue |
| 48 | +Usage: A thread-safe queue that holds elements until a delay has expired. |
| 49 | +- **Example**: |
| 50 | +``` |
| 51 | +DelayQueue<DelayedElement> queue = new DelayQueue<>(); |
| 52 | +queue.put(new DelayedElement()); |
| 53 | +DelayedElement element = queue.take(); |
| 54 | +``` |
| 55 | +
|
| 56 | +## Using ExecutorService |
| 57 | +
|
| 58 | +Creating an ExecutorService |
| 59 | +``` |
| 60 | +Fixed Thread Pool: |
| 61 | + |
| 62 | +ExecutorService executor = Executors.newFixedThreadPool(5); |
| 63 | + |
| 64 | +Single Thread Executor: |
| 65 | + |
| 66 | +ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 67 | + |
| 68 | +Cached Thread Pool: |
| 69 | + |
| 70 | +ExecutorService executor = Executors.newCachedThreadPool(); |
| 71 | + |
| 72 | +Scheduled Thread Pool: |
| 73 | + |
| 74 | +ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); |
| 75 | +``` |
| 76 | +
|
| 77 | +Submitting Tasks |
| 78 | +
|
| 79 | +``` |
| 80 | +Runnable Task: |
| 81 | + |
| 82 | +executor.submit(() -> { |
| 83 | + System.out.println("Task executed"); |
| 84 | +}); |
| 85 | + |
| 86 | +Callable Task: |
| 87 | + |
| 88 | +Future<String> future = executor.submit(() -> { |
| 89 | + return "Task result"; |
| 90 | +}); |
| 91 | +``` |
| 92 | +
|
| 93 | +Shutting Down ExecutorService |
| 94 | +Shutdown gracefully: |
| 95 | +
|
| 96 | +``` |
| 97 | +executor.shutdown(); |
| 98 | +if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { |
| 99 | + executor.shutdownNow(); |
| 100 | +} |
| 101 | + |
| 102 | +Force shutdown: |
| 103 | + |
| 104 | + |
| 105 | +executor.shutdownNow(); |
| 106 | + |
| 107 | +``` |
| 108 | +
|
| 109 | +## Good Practices |
| 110 | +
|
| 111 | +1. Use Appropriate Data Structures |
| 112 | +Choose thread-safe data structures from the java.util.concurrent package. |
| 113 | +Example: Use ConcurrentHashMap instead of HashMap. |
| 114 | +
|
| 115 | +3. Minimize Locking |
| 116 | +Prefer using higher-level concurrency utilities like Semaphore, CountDownLatch, CyclicBarrier over explicit locks. |
| 117 | +Example: |
| 118 | +``` |
| 119 | +Semaphore semaphore = new Semaphore(1); |
| 120 | +semaphore.acquire(); |
| 121 | +try { |
| 122 | + // critical section |
| 123 | +} finally { |
| 124 | + semaphore.release(); |
| 125 | +} |
| 126 | +``` |
| 127 | +
|
| 128 | +3. Use Executors for Thread Management |
| 129 | +Avoid manual thread creation; use ExecutorService for better management. |
| 130 | +Example: |
| 131 | +``` |
| 132 | +ExecutorService executor = Executors.newFixedThreadPool(5); |
| 133 | +executor.submit(() -> { |
| 134 | + // task |
| 135 | +}); |
| 136 | +executor.shutdown(); |
| 137 | +``` |
| 138 | +
|
| 139 | +4. Handle Exceptions in Tasks |
| 140 | +Ensure that tasks submitted to an executor service handle exceptions properly. |
| 141 | +Example: |
| 142 | +``` |
| 143 | +executor.submit(() -> { |
| 144 | + try { |
| 145 | + // task |
| 146 | + } catch (Exception e) { |
| 147 | + e.printStackTrace(); |
| 148 | + } |
| 149 | +}); |
| 150 | +``` |
| 151 | +
|
| 152 | +5. Properly Shutdown ExecutorService |
| 153 | +Always shutdown ExecutorService to release resources. |
| 154 | +Example: |
| 155 | +``` |
| 156 | +executor.shutdown(); |
| 157 | +try { |
| 158 | + if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { |
| 159 | + executor.shutdownNow(); |
| 160 | + } |
| 161 | +} catch (InterruptedException e) { |
| 162 | + executor.shutdownNow(); |
| 163 | +} |
| 164 | +``` |
| 165 | +6. Avoid Blocking Operations in Tasks |
| 166 | +Avoid long-running or blocking operations inside tasks to keep the thread pool responsive. |
| 167 | +Example: |
| 168 | +
|
| 169 | +``` |
| 170 | +executor.submit(() -> { |
| 171 | + // Avoid blocking calls like Thread.sleep() or I/O operations |
| 172 | +}); |
| 173 | +``` |
| 174 | +
|
| 175 | +7. Use Thread-Safe Collections |
| 176 | +Use collections from java.util.concurrent for thread safety. |
| 177 | +Example: |
| 178 | +``` |
| 179 | +ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); |
| 180 | +``` |
| 181 | +
|
0 commit comments