Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Throw an exception to another Thread

I have a java code like this:

private class Uploader implements Runnable
{
    // ...

public void start()
{
    t.start();
}

public void run()
{
        try {

        while(i=in.read())
        {
            output.write(i);    // THIS IS A BLOCKING CALL !!
        }

        } catch(ProtocolException e) { ... }
          catch(IOException e1) { ... }
}

private void restore()
{
        ...
}

private class Checker implements Runnable
{
            // ...

    @Override
    public void run()
    {
                // I WANT (IN A PARTICULAR MOMENT) TO THROW AN
                // EXCEPTION INTO THE Uploader RUN METHOD FROM HERE,
                // IS IT POSSIBLE? 
    }
}
}

The problem is that i have a blocking write() in the Run() method, so I have added a new thread that checks whether or not the connection is transmitting: if it's not trasmitting I want to stop the blocking write() using the exception mechanism (throwing an exception to the other thread's run() method from the checker thread). Is it possible?

EDIT [SOLVED]:

The only way is to brutally close the output stream and to work on the amount of written bits to check whether the connection is transmitting:

private class Uploader implements Runnable
{
    private OutputStream output;

    private int readedBits;

    public void run()
    {
        try {

            while(i=in.read())
            {
                output.write(i);

                readedBits++;
            }

        } catch(IOException e1)
                {   
                    // ENTERS HERE IF RESTORE() IS CALLED
                }
    }

    private void restore()
    {
        try {
            output.close();
        } catch (IOException e) {}

        // Restore connection ....
    }

    private int getReadedBits()
    {   
        return this.readedBits;
    }

    private class Checker implements Runnable
    {
            // ...

        @Override
        public void run()
        {
            while(true)
            {
                try {
                    Thread.sleep(timeout);
                } catch (InterruptedException e1) {}

                if(lastReaded >= getReadedBits())
                    restore();
                else
                    lastReaded = getReadedBits();
            }
        }
    }
}
like image 896
Gino Cappelli Avatar asked Apr 16 '26 01:04

Gino Cappelli


2 Answers

You can make your code honor Thread.interrupt() call. See javadoc of this call.

like image 149
Victor Sorokin Avatar answered Apr 18 '26 13:04

Victor Sorokin


Not exactly what you've asked for but I'd rather use java.nio and
public abstract int select(long timeout) throws IOException
to (not only) detect timeouts.

like image 38
VolkerK Avatar answered Apr 18 '26 14:04

VolkerK