Prev Next

Java / Java Multithreading

Explain Exchanger in Java thread.

Exchanger is a synchronization point at which threads can pair and swap elements between the pair. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return.

An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.

package main.java.tags;

import java.util.concurrent.*;
import java.util.*;

public class ExchangerExample {

	public static void main(String[] args) {

		Exchanger<Integer> exchanger = new Exchanger<Integer>();

		Thread t1 = new MyThread(exchanger, new Integer(5));
		Thread t2 = new MyThread(exchanger, new Integer(10));
		t1.start();
		t2.start();
	}
}

class MyThread extends Thread {

	Exchanger<Integer> exchanger;
	Integer numberToExchange;

	MyThread(Exchanger<Integer> exchanger, Integer message) {
		this.exchanger = exchanger;
		this.numberToExchange = message;
	}

	public void run() {
		try {
			System.out.println(this.getName() + " has value: " + numberToExchange);

			// exchange messages
			numberToExchange = exchanger.exchange(numberToExchange);

			System.out.println("After exchange " + this.getName() + " has value: " + numberToExchange);
		} catch (Exception e) {
		}
	}
}

The above example exchanges Integer objects between a pair of threads. The below is the output.

Thread-0 has value: 5
Thread-1 has value: 10
After exchange Thread-0 has value: 10
After exchange Thread-1 has value: 5

It's right time to invest in Cryptocurrencies Dogecoin! Earn free bitcoins up to $250 now by signing up.

Earn bitcoins upto $250 (free), invest in other Cryptocurrencies when you signup with blockfi. Use the referral link: Signup now and earn!

Using BlockFi, don't just buy crypto - start earning on it. Open an interest account with up to 8.6% APY, trade currencies, or borrow money without selling your assets.


Join CoinBase! We'll both receive $10 in free Bitcoin when they buy or sell their first $100 on Coinbase! Available in India also. Use the referral Join coinbase!


Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Multitasking. Multiprogramming/Multiprocessing. Basic units of execution in concurrent programming. Is concurrency possible on simple single processor systems without multiple processors? Define Processes. Define Threads. What is the default thread of every Java application? Thread Objects. When does Thread Interference occur? How do you create a Thread? Which approach is recommended? Does Thread class implements Runnable? What is the signature of Thread run() method? Define synchronization. Can a thread be interrupted when it is in sleep? Does sleep() method throws any Exception? Can the start method be called twice on the same Thread? (OR) Can the start() method invoked again on the same thread object after start() been called first time? Why do we call Thread.start() method which in turns calls run method? Consumer Producer problem. Difference between Thread.interrupted() and Thread.isInterrupted(). Give few example from Java API that throws InterruptedException. Thread.sleep method() Best practice for "DO Nothing" Strategy for InterruptedException. How do you interrupt an thread that does not call any method that throws InterruptedException? join() method. is join() a overloaded method? Interrupts An example for join(long milliseconds). How do you interrupt an thread that does not call any method that throws InterruptedException? Explain the interrupt mechanism. Can run() method throw exception? Difference between sleep and wait method in Java. Is ++ (increment) operator thread-safe in Java? What is thread starvation? Does pressing Control-C causes InterruptedException in Java? What is livelock in multithreading? Explain race condition in multithreading. What causes starvation in threads? Difference between deadlock and livelock in Java multithreading. What is Slipped Condition in multithreading? What is Intrinsic Lock in Java multithreading? Explain Guarded Blocks in Java. What is BLOCKED state of a thread? Different states of a Java thread. Difference between thread state WAIT and BLOCKED. Difference between synchronizing a static method and a non static method in Java. What is reentrant synchronization in Java? What is Reentrant lock in Java? Can a thread hold more than one lock at the same time? Difference between synchronized method and synchronized block in Java. What is Runnable in Java? Difference between start and run methods in Java Thread. Define Critical section in Java multi-threading. Explain IllegalMonitorStateException in Java multi-threading. What is Spurious Wakeups in Java threads? What is Daemon thread in Java? Difference between Daemon and Non Daemon thread in Java. Difference between a wait() and sleep() in Threads. Difference between concurrency and parallelism. Explain wait(), notify() and notifyAll() methods in Java threading. Can a thread wait on multiple objects in Java? What is mutex in Java? Explain semaphore in Java. Difference between Mutex and Semaphore in Java. Difference between notify and interrupt in Java. Difference between notify and notifyAll in Java. When the lock is released after notify/notifyAll is called? Why do we use ReentrantLock over synchronized (this)? Define Liveness in Java Thread. How threads communicate with each other? Difference between synchronized and volatile keyword in Java. Explain Thread Priority. What is Thread Scheduler? Define time slicing. Define context-switching in multi-threading. Which is preferred - Synchronized method or Synchronized block? Why wait, notify and notifyAll are declared in Object class and not in Thread class? What is Thread Group in Java? Explain setUncaughtExceptionHandler method of Java Thread class. What is Thread dump? Explain about jstack tool. How to debug and analyse Thread deadlock? Can we not override run method when we extend Thread class? Define Java thread pool. Advantages of using threadpool. What are atomic classes in Java Concurrency API? What is Lock interface in Java Concurrency API? Define preemptive scheduling. What is the priority for Daemon threads? Explain yield() method of a thread. Can 2 threads call different synchronized instance methods of same Object? What is thread leak in Java? What is CountDownLatch in Java? Applications of CountDownLatch in Java thread. Explain CyclicBarrier in Java thread. Difference between wait-notify and CountDownLatch. How do you create an immutable class in Java? What is the purpose of the class java.lang.ThreadLocal? Explain volatile keyword in Java. Explain fork/join framework in Java thread. Explain Fork-Join framework API. Explain Exchanger in Java thread. Difference between ReadLock and WriteLock in Java ReentrantReadWriteLock. General practice for releasing lock while using Lock implementation in Java. Advantages of using Lock implementations in Java threading. Difference between Runnable and Callable interfaces in Java. What is the Thread’s interrupt flag? What is FutureTask Class? What are some common problems you face in multi-thread programming? Limitations of Future. What is the enhanced version of Future (or) alternative to Future? Difference between green and native threads. More questions...
Show more question and Answers...

Java Multithreading part II

Comments & Discussions