|
| 1 | +--- |
| 2 | +id: "6d265fc2-1b92-417b-a1dd-9150d4985a1b" |
| 3 | +slug: "wait-notify-to-blocking-queue" |
| 4 | +title: "Wait and notify queues to BlockingQueue" |
| 5 | +category: "concurrency" |
| 6 | +difficulty: "intermediate" |
| 7 | +jdkVersion: "5" |
| 8 | +oldLabel: "Manual wait and notify" |
| 9 | +modernLabel: "BlockingQueue" |
| 10 | +oldApproach: "Manual wait and notify" |
| 11 | +modernApproach: "BlockingQueue" |
| 12 | +oldCode: |- |
| 13 | + synchronized (queue) { |
| 14 | + while (queue.isEmpty()) { |
| 15 | + queue.wait(); |
| 16 | + } |
| 17 | + Job job = queue.removeFirst(); |
| 18 | + process(job); |
| 19 | + } |
| 20 | +modernCode: |- |
| 21 | + BlockingQueue<Job> queue = new LinkedBlockingQueue<>(); |
| 22 | +
|
| 23 | + Job job = queue.take(); |
| 24 | + process(job); |
| 25 | +summary: "Replace hand-written producer-consumer coordination with BlockingQueue." |
| 26 | +explanation: "Correct wait/notify code requires a shared monitor, condition loops,\ |
| 27 | + \ matching notifications, and careful interruption handling. BlockingQueue encapsulates\ |
| 28 | + \ those rules and provides blocking, timed, and non-blocking operations for producer-consumer\ |
| 29 | + \ workflows. Calls such as put() and take() remain interruptible." |
| 30 | +whyModernWins: |
| 31 | +- icon: "🛡" |
| 32 | + title: "Safer coordination" |
| 33 | + desc: "The queue owns the locking and condition signaling." |
| 34 | +- icon: "👁" |
| 35 | + title: "Clear intent" |
| 36 | + desc: "put() and take() directly express producer-consumer behavior." |
| 37 | +- icon: "🎛" |
| 38 | + title: "Built-in policies" |
| 39 | + desc: "Choose bounded capacity, fairness, timeouts, or non-blocking operations." |
| 40 | +support: |
| 41 | + state: "available" |
| 42 | + description: "Widely available since JDK 5 (2004)" |
| 43 | +prev: "concurrency/lock-free-lazy-init" |
| 44 | +next: "concurrency/thread-stop-to-cooperative-cancellation" |
| 45 | +related: |
| 46 | +- "concurrency/executor-try-with-resources" |
| 47 | +- "concurrency/structured-concurrency" |
| 48 | +- "concurrency/virtual-threads" |
| 49 | +tags: |
| 50 | +- concurrency |
| 51 | +docs: |
| 52 | +- title: "BlockingQueue" |
| 53 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/BlockingQueue.html" |
| 54 | +- title: "LinkedBlockingQueue" |
| 55 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/LinkedBlockingQueue.html" |
0 commit comments