The thread-per-request approach
In Chapter 1, Getting Started with Network Programming, we illustrated a simple multithreaded echo server. This approach is reintroduced here to provide a foundation for the use of threads in the remainder of the chapter.
The thread-per-request server
In this example, the server will accept requests for prices when given the name of a part. The implementation will use the ConcurrentHashMap
class that supports concurrent access to the part name and price. In a multithreaded environment, concurrent data structures, such as the ConcurrentHashMap
class, handle operations without the potential for data corruption. Also, this map is an example of caching, which can be useful in improving the performance of applications.
We start with the declaration of the server as follows. The map is declared as static because only one instance is needed for the server. The static initialization block initializes the map. The main
method will use the ServerSocket
class to accept...