Java Reference
In-Depth Information
20.5.4 The SimData class
SimData is a small but important class. Simulation data is stored in it when-
ever storeData() is called by the Simulation object as the calcula-
tion runs. SimData must also be ready to provide the most recent set of
results whenever the server calls getResults() responding to a client call
to Server.retrieveData() .
SimData methods can be called by two different threads - the simulation
thread, which calls storeData() periodically, and the main server thread, which
calls getResults() upon request from the client. Therefore SimData must
be careful to avoid thread collisions. In particular, requests to retrieve data must
not overlap requests to store data. This situation is easily handled by Java's syn-
chronization features.
SimData internally maintains two private arrays - one for input data and one
for output data. These are created at construction time.
public SimData () {
fInputData = new float [INSIZE];
fOutputData = new float [OUTSIZE];
}
where INSIZE and OUTSIZE are constants that give the required sizes of the
input and output arrays.
During storeData() , the supplied data array from the calculation is copied
to the private fOutputData array and the latest array of input data is returned:
public synchronized float[] storeData (float[] data) {
System.arraycopy (data, 0, fOutputData, 0, OUTSIZE);
return fInputData;
}
When the server calls getResults() , the fOutputData array is returned.
At the same time, a new input array is received and copied to the private
fInputData array:
public synchronized float[] getResults (float[] indata) {
System.arraycopy (indata, 0, fInputData, 0, INSIZE);
return fOutputData;
}
In these methods we see another advantage of using arrays of float sas
data containers rather than custom classes. The use of the optimized System.
arraycopy() method to copy array elements is very fast. Cloning objects con-
taining structured data is not nearly as fast. Since the getting and setting of the
data arrays is a frequently occurring event, the time saved here by using float
arrays instead of custom classes can be significant, especially in a simulation that
involves hundreds or more data elements.
Search WWH ::




Custom Search