Java Reference
In-Depth Information
Obtaining a PreparedStatement
Other than allowing statements to be repeated, the other major function provided by the
RepeatableStatement
class is the ability to allocate
PreparedStatement
objects to threads. Two threads cannot use the same
PreparedStatement
object at
the same time. To keep threads from using the same
PreparedStatement
object, the
obtainStatement
and
releaseStatement
functions are used.
The first thing that the
obtainStatement
function does, is to check to see if it
can acquire the
mutex
. This prevents two threads from calling
obtainStatement
at
exactly the same time.
PreparedStatement result = null;
try {
this.mutex.acquire();
If there are no extra statements already in the cache, then create a new
PreparedStatement
.
if (this.statementCache.size() == 0) {
result = this.manager.getConnection().prepareStatement(this.sql);
If there is an extra
PreparedStatement
in the cache, then return that
PreparedStatement
and remove it from the cache.
} else {
result = this.statementCache.get(0);
this.statementCache.remove(0);
}
} catch (InterruptedException e) {
return null;
Once we are done, we can release the
mutex
.
} finally {
this.mutex.release();
}
return result;
Once you are finished with the
PreparedStatement
that we obtained, call
releaseStatement
to return it to the cache.
Releasing a PreparedStatement
When a
PreparedStatement
is released by calling
releaseStatment
,
the
PreparedStatement
is not actually released. Rather, it is simply returned to the
PreparedStatement
cache. This saves the program the overhead of allocating and
releasing large numbers of
PreparedStatement
objects.