General Java Questions IV
It looks safe, but there s a subtle flaw...
Answer 2: Suppose you start with a vector of ten elements. On the tenth iteration i
will have the value 9 and the test i < vector.size() will succeed.
Now suppose the thread scheduler chooses this moment to pause the current thread
and let another thread run. This second thread removes an object from the vector.
Now when the first thread resumes, the vector has only nine elements and 9 is no
longer a valid index.
The elementAt() method will fail mysteriously with an
ArrayIndexOutOfBoundsException. The thing you must realize is that although the
size() and elementAt() methods are both thread safe, using them together this way
isn t.
The vector s synchronization lock is released between the two calls that give the
second thread a chance to modify the data. The solution is to lock the vector for the
entire loop like this:
synchronized (vector) {
for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.elementAt(i));
}
}
Now if another threads attempt to modify the vector while the loop is executing, it will
be forced to wait until the loop ends and the vector s lock is released.
John Skeet, Mike
Q: How do I copy one array to another?
Given that I have an byte array defined like this:
byte byteSmall = new byte[23];
and another larger byte array defined like this:
byte byteBig = new byte[30];
How do I copy byteSmall into byteBig starting at index 7 without a for loop like this:
for(int i = 0; i < 23; i++){
byteBig[i + 7] = byteSmall;
}
?
Answer: See System.arraycopy:
"Copies an array from the specified source array, beginning at the specified position,
to the specified position of the destination array. A subsequence of array
components are copied from the source array referenced by src to the destination
array referenced by dst. The number of components copied is
equal to the length argument. The components at positions srcOffset through
srcOffset+length 1 in the source array are copied into positions dstOffset through
dstOffset+length 1, respectively, of the destination array.
If the src and dst arguments refer to the same array object, then the copying is
performed as if the components at positions srcOffset through srcOffset+length 1
were first copied to a temporary array with length components and then the contents
of the temporary array were copied into positions dstOffset through
dstOffset+length 1 of the argument array."
file:///F|/a_jsite/350_tips/general_java IV.htm (4 of 10) [2001 07 08 11:24:54]
footer
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved