If you look at this code out of context there is no good explanation for that "alias". It is simply redundant code or poor code style.
But the context is that BufferedInputStream
is a class that can be subclassed, and that it needs to work in a multi-threaded context.
The clue is that in
is declared in FilterInputStream
is protected volatile
. That means that there is a chance that a subclass could reach in and assign null
to in
. Given that possibility, the "alias" is actually there to prevent a race condition.
Consider the code without the "alias"
private InputStream getInIfOpen() throws IOException {
if (in == null)
throw new IOException("Stream closed");
return in;
}
- Thread A calls
getInIfOpen()
- Thread A evaluates
in == null
and sees that in
is not null
.
- Thread B assigns
null
to in
.
- Thread A executes
return in
. Which returns null
because a
is a volatile
.
The "alias" prevents this. Now in
is read just once by thread A. If thread B assigns null
after thread A has in
it doesn't matter. Thread A will either throw an exception or return a (guaranteed) non-null value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…