Skip to main content

Exchanger in Java's Concurrent API


The Exchanger class in Java's java.util.concurrent package offers a unique synchronization mechanism for concurrent programming. It facilitates exchange of objects between two threads in a pair, acting as a rendezvous point where both threads must arrive with their respective objects before any actual exchange occurs.

Key Concepts:

  • Object Exchange: Each thread presents an object upon calling exchange(). When both threads arrive, they exchange their objects and proceed.
  • Synchronization: exchange() blocks the calling thread until its partner arrives, ensuring data consistency and preventing race conditions.
  • Bidirectional Queue: Consider Exchanger as a two-slot circular buffer where threads take and put items alternatively.
  • Generic Type: Accommodates exchange of objects of any type (T).

Methods:

  • exchange(T object): Exchanges the given object with another thread's and returns the received object. Blocks until another thread arrives.
  • exchange(T object, long timeout, TimeUnit unit): Similar to exchange(), but with a timeout. Throws TimeoutException if the wait exceeds the specified duration.

Common Use Cases:

  • Producer-Consumer: Efficient data transfer between producing and consuming threads, avoiding busy waiting.
  • Pipeline Processing: Implement stages in a processing pipeline where data is passed between stages.
  • Buffer Management: Allocate buffers shared between threads, one waiting for an empty buffer while the other fills it.

Example:

Java
import java.util.concurrent.Exchanger;

public class ExchangerExample {

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        Thread producer = new Thread(() -> {
            try {
                String message = "Hello from producer!";
                String received = exchanger.exchange(message);
                System.out.println("Producer received: " + received);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                String received = exchanger.exchange(null);
                System.out.println("Consumer received: " + received);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();
    }
}

Additional Notes:

  • Exchanger is generally not suitable for frequent exchanges due to its blocking nature. Consider less disruptive mechanisms for high-performance scenarios.
  • For more complex data sharing patterns, alternative synchronization constructs like BlockingQueue or concurrent data structures might be more appropriate.

Comments

Popular posts from this blog

Safety property that a deadlock can never occur

Identified four necessary conditions for a deadlock to occur 1. Mutual Exclusion. The nodes claim exclusive control of the resources they require. 2. Wait for. Tasks hold resources already allocated to them while waiting for additional resources. 3. No preemption. Resources cannot be forcibly removed from the tasks holding them until the resources are used to completion. 4. Cyclic Wait. A cyclic chain of tasks exists, such that each task holds one or more resources that are being requested by the next task in the chain. References: For information about system deadlocks please refer: E. G. Coffman, M. Elphick, and A. Shoshani. System Deadlocks

OWASP API Security Top 10 vulnerabilities 2023

API Security Do's and Don'ts Don't trust input data for an API and do validate all inputs. Ensure you understand security and keep sensitive data out of code. Don't hardcode keys/tokens Don't reveal useful info in error messages. Don't have hidden/unadvertised features. Don't filter data in UI - control at app level Don't confuse authentication and authorization Always use API gateways to control access and traffic Do require API documentation. Do expect users/hackers to find and use undocumented endpoints Do continuous testing - attack simulation, test configs, fuzzing, injections OWASP API Security Top 10 Vulnerabilities 2023 API-1:2023 - Broken Object Level Authorization: BOLA is still the leading vulnerability that plagues APIs. When data objects do not have sufficient access controls in place, resources can be accessed by unauthorized users. API-2:2023 - Broken Authentication  Broken Authentication contains all vulnerabilities associated with auth...
Program to print items in single linkedlist in Pendulum order  Single linked list pendulum in java There are sequence of numbers in a single linked list and display the result in pendulum format Input : 1 2 3 4 5 6 7 8 Output : 1 8 2 7 3 6 5 4 Solution :  https://github.com/Bonu/datastructures/blob/main/SingleLinkedListPendulum.java Below is the manual approach: Input: 1 2 3 4 5 6 7 Iteration 1: 1 2 3 4 5 6 7 Iteration 2: 1 7 2 3 4 5 6 Iteration 3: 1 7 2 6 3 4 5 Iteration 4: 1 7 2 6 3 5 4