Page 46 - The Definitive Guide to Building Java Robots
P. 46
Preston_5564C02.fm Page 27 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 27
Table 2-2. Pros and Cons of Concurrent Usage
Solution Pro Con
Create serial port inside each Each class is self-contained. Concurrent use likely;
dependent object. plus, application will throw
PortInUseException. Closing
of serial port has to be done
via method call to invoking
object.
Create serial port outside of Concurrent use limited to Each class requires SerialPort
consuming objects. current thread. Closing of to be sent in constructor. Not
serial port can be done outside thread-safe.
of individual objects.
Create single class that has Self-contained. Thread Safe. Poor reuse.
control of all required actions Closing of port managed
of serial port. inside of class.
Use a singleton of serial port Class is self-contained. Limited to single serial port
inside each dependent object. Concurrent use is limited to regardless of com ID.
JVM and is thread-safe.
Closing of objects is done
outside of individual objects.
Use a singleton of serial ports Class is self-contained. None.
inside a resource pool of all Concurrent use is limited to
available serial ports. JVM and is thread-safe. The
closing of objects can be done
outside of individual objects.
Can request any available
serial port system it can find.
Code Objective
The objective of this example is to show how to create a resource pool of serial ports without
getting conflicts if multiple objects want to access them at once.
Code Discussion
The only field in SingleSerialPort class is a vector: portsInUse. This vector is a collection of the
currently initialized serialPorts. Because a vector is synchronized, this ensures that the ports
are accessed in a thread-safe manner.
I created a private constructor to prevent initialization. All StandardSerialPorts will be
returned via the getInstanceMethods.
The getInstance method uses the name of the SerialPort (COM1 or stty1) to identify itself
and either create a new one or return a port already in the pool.
Finally, the close() method removes the ports from the pool and closes them. (See
Example 2-5.)