Re: Timeout question on a socket thread
On Jul 30, 12:19 pm, RVic <rvinc...@hotmail.com> wrote:
But say I declare something as final, and initialize it to null in the
declaration (so I can access it in y finally block), can I
subsequently assign it
final OutputStream output = null;
try {
output = socket.getOutputStream(); //is this legitimate?}fi=
nally{
output = null; //=
is this legitimate?
No, it is not legitimate. So don't assign 'null' to 'output'.
That makes the lifetime of 'output' exactly that of the instance of
which it's a member.
This is a good thing.
Here's one of several ways to use such a thing:
public class Foo
{
...
public void doSomething()
{
final OutputStream output;
try
{
output = socket.getOutputStream();
}
catch ( IOException exc )
{
logger.error( "Cannot open output stream" );
return;
}
Runnable task = new Runnable()
{
@Override public void run()
{
byte [] inputBuf = new byte [BUFSIZE];
try
{
for ( int bRead;
(bRead = inputBuffered.read( inputBuf )) >= 0;
)
{
output.write( inputBuf. 0, bRead );
}
}
catch ( IOException ioe )
{
logger.error( "Cannot write to output" );
}
}
};
try
{
Thread tt = new Thread( task );
tt.start();
...
tt.join();
}
finally
{
try
{
output.close();
}
catch ( IOException ioe )
{
logger.error( "Cannot close stream" );
}
}
...
This is obviously incomplete and untested, but it should give the
idea.
--
Lew