Java Reference
In-Depth Information
E
X
C
H
A
N
G
E
R
An object
An object
Figure 6-15. Two threads meet at exchange point and exchange objects
The Exchanger class provides an implementation for an exchanger synchronizer. It has one constructor, which
takes no arguments. You can create an exchanger like so:
Exchanger exchanger = new Exchanger();
The exchanger created in the above statement will let two threads exchange any type of Java objects. However,
if you know the type of the object the threads will exchange, you can specify that using generics while creating the
exchanger like so:
Exchanger<ObjectType> exchanger = new Exchanger<ObjectType>();
The Exchanger class has only one method, exchange() . When a thread is ready to exchange an object with
another thread, it calls the exchange() method of the exchanger and waits for another thread to exchange the object.
A thread that is waiting to exchange an object may be interrupted. Another overloaded version of the exchange()
method accepts a timeout period. If the timeout period is specified, the thread calling this method will wait for
another thread to exchange an object until the timeout period is elapsed. The exchange() method takes the object to
pass on to another thread as an argument and it returns the object passed by another thread. You call the exchange()
method like so:
objectReceived = exchanger.exchange(objectedPassed);
Listing 6-44, Listing 6-45, and Listing 6-46 demonstrate the use of an exchanger in building a producer-consumer
system that exchanges a buffer, which is an ArrayList of Integer objects. To declare an array list of integer objects,
you have to declare it as
ArrayList<Integer> buffer = new ArrayList<Integer>();
In Listing 6-46, you have created an exchanger as
Exchanger<ArrayList<Integer>>exchanger = new Exchanger<ArrayList<Integer>>();
The type declaration Exchanger<ArrayList<Integer>> indicates that the exchanger will let two threads exchange
objects of type ArrayList<Integer> . You can also note that the type declarations in the ExchangerProducer and
ExchangerConsumer classes match the above declaration. The producer fills up the data and waits for some time to
give user an impression that it is really filling up data. It waits for the consumer to exchange the filled buffer with an
empty buffer from the consumer. The consumer does the opposite. It waits for the producer to exchange the buffer.
When it gets a full buffer from the producer, it empties the buffer and again waits for the producer to exchange its
empty buffer for a full one. Since the producer and consumer run in infinite loops, the program will not end. You will
have to end the program manually. You will get a similar output to that shown for Listing 6-46.
 
Search WWH ::




Custom Search