Video tayyorlanmoqda

Strong Junior 🧵 Concurrency

BlockingQueue yordamida producer-consumer'ni qanday qurasiz?

Producer put() bilan navbatga qo'yadi, consumer take() bilan oladi. Navbat to'lsa producer, bo'sh bo'lsa consumer avtomatik kutadi — wait/notify'ni qo'lda yozish shart emas.

📖 Javob

BlockingQueue<Event> queue = new ArrayBlockingQueue<>(500);

// producer
Thread producer = Thread.ofPlatform().name("reader").start(() -> {
    try {
        for (Event e : readEvents()) {
            queue.put(e);              // to'lsa kutadi
        }
        queue.put(Event.POISON);       // "boshqa yo'q" signali
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
});

// consumer
Thread consumer = Thread.ofPlatform().name("writer").start(() -> {
    try {
        while (true) {
            Event e = queue.take();    // bo'sh bo'lsa kutadi
            if (e == Event.POISON) break;
            save(e);
        }
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
});

Metodlar to'rt xil xatti-harakatga ega: add/remove exception tashlaydi, offer/poll darhol false/null qaytaradi, put/take bloklaydi, offer(e, timeout)/poll(timeout) vaqt bilan kutadi.

Qaysi navbat: ArrayBlockingQueue — sig'imi qat'iy, LinkedBlockingQueue — sig'imini albatta bering (default Integer.MAX_VALUE), PriorityBlockingQueue — tartib bo'yicha.

"Poison pill" — consumer'ni toza to'xtatishning oddiy usuli. Consumer bir nechta bo'lsa, har biriga bittadan qo'yish kerak.