Java Reference
In-Depth Information
C board is the unique identifier that we'll use for a key field in this example. Con-
ceptually, we'll have a hash table entry for every board. Each hash table entry is an
executed command that has the whole list of boards.
D cached is a variable that will tell us whether the command was retrieved from the
cache, and we can display that status on the JSP . Of course, in practice, this
attribute is not necessary.
E Danger! boardCache is declared as a static attribute. That means only one copy
exists, attached to the class object. Whenever we access this attribute, we must do
so in synchronized code, which means that only one method can use our hash
table at a time. Later in the chapter, we'll introduce read-write locks, which will
provide more concurrent access without the loss of thread safety.
F Next, we have the initialize method. We initialize and validate, as usual. We are
slimmed down somewhat, because the database connections and validation are
handled in the sister command.
G The first time any object uses the hash table, it will need to be initialized, but only
the first time because it is a static variable.
H Next is the invalidate method. This method is used whenever the board's list of
posts can change. In our case, we'll need to call invalidate whenever we add a
new top-level post.
I Next is the execute method. We fire the logic wrapped by the command, as usual.
J This code section is synchronized because it writes to the hash table. If a command
with our key is in the hash table, then we've just about completed this execute
method. Compare that with the intialize and execute methods in the previous
edition of ShowBoardCommand , which validated the input parameters, connected to
a database, executed a query, and fetched the results of the query to populate the
input variables. The system was also working hard, with several round-trip com-
munications to the database server, an expensive database connection, and plenty
of expensive string manipulation.
1)
We check to see if we found the requested board in the cache, also called a cache
hit . If not, we simply create the command, process the sets, initialize, and execute,
just like before. We've added a layer of complexity in front of our regular com-
mand in case our cache doesn't get a hit. Remember that this case is the exception.
For most applications, hits of 90 percent or more in the cache are not out of the
ordinary. For our bulletin board example, the entire message board might fit into
memory, so we can probably expect to see much higher hit rates. As long as our
Search WWH ::




Custom Search