Chapter 4. Selectors
Life is a series of rude awakenings.
In
this chapter, we’ll explore selectors. Selectors
provide the ability to do
readiness
selection,
which enables
multiplexed
I/O. As described in Chapter 1, readiness selection and multiplexing make it
possible for a
single thread to efficiently manage many
I/O channels simultaneously. C/C++ coders have had
the POSIX
select( ) and/or
poll( ) system calls in their toolbox for many
years. Most other operating systems provide similar
functionality. But readiness selection was never available to Java
programmers until JDK 1.4. Programmers whose
primary body of experience is in the Java environment may not have
encountered this I/O model before.
For an illustration of readiness selection, let’s return to the drive-through bank example of Chapter 3. Imagine a bank with three drive-through lanes. In the traditional (nonselector) scenario, imagine that each drive-through lane has a pneumatic tube that runs to its own teller station inside the bank, and each station is walled off from the others. This means that each tube (channel) requires a dedicated teller (worker thread). This approach doesn’t scale well and is wasteful. For each new tube (channel) added, a new teller is required, along with associated overhead such as tables, chairs, paper clips (memory, CPU cycles, context switching), etc. And when things are slow, these resources (which have associated costs) tend to sit idle.
Now imagine a different scenario ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access