27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

General <strong>Java</strong> Questions I<br />

The Vector class is thread-safe. By that I mean that there is no way to corrupt the<br />

internal representation of the data by accessing the vector from more than one<br />

thread. However, it is still possible, very easy in fact, to use a vector in a way that is<br />

not thread safe.<br />

Consider this code:<br />

for (int i = 0; i < vector.size(); i++) {<br />

System.out.println(vector.elementAt(i));<br />

}<br />

It looks safe, but there's a subtle flaw...<br />

Answer 2: Suppose you start with a vector of ten elements. On the tenth iteration i will<br />

have the value 9 and the test i < vector.size() will succeed.<br />

Now suppose the thread scheduler chooses this moment to pause the current thread<br />

and let another thread run. This second thread removes an object from the vector.<br />

Now when the first thread resumes, the vector has only nine elements and 9 is no<br />

longer a valid index.<br />

The elementAt() method will fail mysteriously with an<br />

ArrayIndexOutOfBoundsException. The thing you must realize is that although the<br />

size() and elementAt() methods are both thread-safe, using them together this way<br />

isn't.<br />

The vector's synchronization lock is released between the two calls that give the<br />

second thread a chance to modify the data. The solution is to lock the vector for the<br />

entire loop like this:<br />

synchronized (vector) {<br />

for (int i = 0; i < vector.size(); i++) {<br />

System.out.println(vector.elementAt(i));<br />

}<br />

}<br />

Now if another threads attempt to modify the vector while the loop is executing, it will<br />

be forced to wait until the loop ends and the vector's lock is released.<br />

--<br />

John Skeet, Mike<br />

this advice first was published on comp.lang.java.programmer<br />

Q: How do I copy one array to another?<br />

Given that I have an byte array defined like this:<br />

byte byteSmall = new byte[23];<br />

and another larger byte array defined like this:<br />

byte byteBig = new byte[30];<br />

How do I copy byteSmall into byteBig starting at index 7 without a for loop like this:<br />

for(int i = 0; i < 23; i++){<br />

byteBig[i + 7] = byteSmall;<br />

}<br />

?<br />

Answer: See System.arraycopy:<br />

"Copies an array from the specified source array, beginning at the specified position,<br />

file:///F|/350_t/350_tips/general_java-I.htm (25 of 31) [2002-02-27 21:18:17]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!