java synchronousqueue examples

www.‮ditfigi‬ea.com

SynchronousQueue is a special type of blocking queue in Java that is mainly used for passing data between threads in a producer-consumer fashion. It's different from other blocking queues like ArrayBlockingQueue or LinkedBlockingQueue in that it has no storage capacity - every put operation must be immediately followed by a take operation, and vice versa.

Here are some examples of using SynchronousQueue in Java:

  1. Passing data between two threads
SynchronousQueue<String> queue = new SynchronousQueue<>();

// Thread 1 - producer
new Thread(() -> {
    try {
        queue.put("Hello");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

// Thread 2 - consumer
new Thread(() -> {
    try {
        String message = queue.take();
        System.out.println(message);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

In this example, we create a new SynchronousQueue and start two threads - one that puts a message into the queue and one that takes the message from the queue and prints it out. Since the SynchronousQueue has no storage capacity, the put and take operations must happen in separate threads for the program to work correctly.

  1. Handing off tasks between multiple threads
SynchronousQueue<Runnable> queue = new SynchronousQueue<>();

// Create a pool of worker threads
ExecutorService pool = Executors.newFixedThreadPool(4);

// Start the worker threads
for (int i = 0; i < 4; i++) {
    pool.execute(() -> {
        while (true) {
            try {
                // Wait for a task to be put into the queue
                Runnable task = queue.take();
                // Execute the task
                task.run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

// Submit some tasks to the queue
for (int i = 0; i < 10; i++) {
    final int taskId = i;
    queue.put(() -> {
        System.out.println("Task #" + taskId + " executed by thread " + Thread.currentThread().getName());
    });
}

In this example, we create a SynchronousQueue to pass Runnable tasks between multiple worker threads. We create a pool of four worker threads and start them running in an infinite loop, waiting for tasks to be put into the queue. We then submit ten tasks to the queue, each of which prints a message to the console indicating that it has been executed by a worker thread.

Overall, SynchronousQueue is a useful tool for passing data between threads in a producer-consumer fashion, and can be used in a variety of scenarios where tasks or messages need to be handed off between threads.