Solved

How to stop an IO block from another thread?

Posted on 2004-08-22
38
2,445 Views
Last Modified: 2008-01-09
This is a J2me program:
The main thread:
sendUDP = new udpThread(display);
try
{
      Thread.sleep(20000);
}
catch(Exception kk)
{}
sendUDP.closeIt();

IO Thread:
public void run()
{
httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
httpConnection.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
httpConnection.setRequestProperty("Content-Language", "en-CA");
httpConnection.setRequestProperty("Connection","Keep-Alive");
//in.close();
in = httpConnection.openInputStream();
while ((inChar = in.read()) != -1)
{          
      inBuffer.append((char)inChar);
}
}

public void closeIt()
{
      try
      {
            System.out.println("close");
            in.close();
            httpConnection.close();
            httpConnection = null;
      }
      catch (Exception dd)
      {
            System.out.println(dd);
      }
}


But the above code seems like doesn't close the http connection. Why?

thanks
0
Comment
Question by:hawkly
  • 17
  • 14
  • 4
  • +1
38 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 25 total points
ID: 11867709
Can be difficult to break out of IO blocking but try

otherThread.interrupt();
httpConnection.close();
httpConnection = null;
0
 
LVL 92

Expert Comment

by:objects
ID: 11867813
> But the above code seems like doesn't close the http connection. Why?

it should do, what makes you think otherwise?
0
 

Author Comment

by:hawkly
ID: 11868772
>> it should do, what makes you think otherwise?

because it doesn't throw any exception when i close the http connection.
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 92

Expert Comment

by:objects
ID: 11868843
> because it doesn't throw any exception when i close the http connection.

are you referring to your run method()?
perhaps it has already completed.

0
 

Author Comment

by:hawkly
ID: 11868939
>> are you referring to your run method()?
yes

>> perhaps it has already completed.
i can confirm that the thread haven complete yet.

Is't possible to use timer to interrupt the IO block (in IO Thread)? E.g.
public void run()
{
      try
      {
            if (httpConnection != null)
            {
                  in.close();
                  httpConnection.close();
                  httpConnection = null;
            }
      }
      catch (Exception hh)
      {
      }
}

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11869214
but your alreadyn closing the connection (aren't you?)
0
 

Author Comment

by:hawkly
ID: 11876978
FYI, the http server will hold the connection for about 30 minutes (write by my colleage).

My problem is:
1. when i force the program to close the http connection and it doesn't throw any exception.
2. after i close the http connection and the server still can response to me and my program still can get the result. very strange thing.
0
 
LVL 92

Expert Comment

by:objects
ID: 11876991
why do you keep reading after its closed?
just set in to null and test for it in your read loop.
0
 

Author Comment

by:hawkly
ID: 11877331
>> why do you keep reading after its closed?
Sorry, can't get what you mean.

in = httpConnection.openInputStream();
while ((inChar = in.read()) != -1)
{          
     inBuffer.append((char)inChar);
}

The IO thread is block at here, when i call the below and it doesn't throw any exception.
in.close();
httpConnection.close();
httpConnection = null;
0
 

Author Comment

by:hawkly
ID: 11877356
>> after i close the http connection and the server still can response to me and my program still can get the result. very strange thing.

What i mean here is when i call the below code the program seems like still waiting for an IO. Because i can get the response from the server after 30 minutes.

in.close();
httpConnection.close();
httpConnection = null;
0
 
LVL 92

Expert Comment

by:objects
ID: 11877365
Have you got a timeout set on the connection?

And what is the cause of the blocking, ie. why isn't the server returning any data.
What excatly is the client talking to?

0
 
LVL 92

Expert Comment

by:objects
ID: 11877388
> What i mean here is when i call the below code the program seems like still waiting for an IO.

I was wondering how it was blocked, and the server was still returning data :)
0
 

Author Comment

by:hawkly
ID: 11877470
>> Have you got a timeout set on the connection?
Yes, as below code.
httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);

API description from http://www.kickjava.com/?http://www.kickjava.com/3145.htm
public static Connection open(String name, int mode, boolean timeouts) throws IOException

The Connection open is throws the IOException so is't this is the cause i can't get the exception when i close it?

If so, then how can i catch the exception?

Thanks
0
 
LVL 92

Assisted Solution

by:objects
objects earned 50 total points
ID: 11877517
not sure whether that timeout just applies to the connect or not. will see what I can find.

Besides the fact that the blocked read is not throwing an exception what problems are you having. As the threads is not going to read anymore data once its closed regardless.
0
 

Author Comment

by:hawkly
ID: 11877536
Actually what i want is try to reconnect to the server when i get an IO exception.
0
 

Author Comment

by:hawkly
ID: 11877542
But now i'm facing a problem that is when i close the connection it doesn't throw an exception so that i can't connect again to the server.
0
 
LVL 92

Expert Comment

by:objects
ID: 11877617
> so that i can't connect again to the server.

Why not, you just need to start a new thread.
0
 

Author Comment

by:hawkly
ID: 11877679
>> Why not, you just need to start a new thread

public void run()
{
     while(true)
     {
          try
          {
               httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
               httpConnection.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
               httpConnection.setRequestProperty("Content-Language", "en-CA");
               httpConnection.setRequestProperty("Connection","Keep-Alive");
               in = httpConnection.openInputStream();
               while ((inChar = in.read()) != -1)
               {          
                    inBuffer.append((char)inChar);
               }
          }  
          catch(Exception e)
          {
          }  
     }
}


Can i do like this?

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11877716
not if its blocked no.
0
 

Author Comment

by:hawkly
ID: 11877738
then what should i do?
i thought if i close the connection then it will throw an error so that it will try to connect to the server again.
0
 
LVL 92

Expert Comment

by:objects
ID: 11877793
Starting a new connection will reconnect.

Thread connect = new Thread(this);
0
 

Author Comment

by:hawkly
ID: 11877948
>> Starting a new connection will reconnect.

will it use too much memory if i always create new thread and didn't kill the old thread?

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11877971
Depends on how often connections to the server get hung.
The thread should eventually end though once the thread unblocks.
0
 

Author Comment

by:hawkly
ID: 11878017
just wonderign why i call the connection.close() method and the program doesn't throw exception and exit the IO block.
0
 
LVL 92

Expert Comment

by:objects
ID: 11878087
I guess cause its blocked :)

0
 

Author Comment

by:hawkly
ID: 11878253
>> I guess cause its blocked

Is't possible to interrupt it?

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11878288
appears not
0
 

Author Comment

by:hawkly
ID: 11878327
ok, thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11879050
>>Is't possible to interrupt it?

If you're prepared to use 1.5 there concurrency classes that can be stopped even if blocked in IO
0
 

Author Comment

by:hawkly
ID: 11888387
>> If you're prepared to use 1.5 there concurrency classes that can be stopped even if blocked in IO

I'm using j2me :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11890076
>>I'm using j2me :)

Ah  - in that case it could be tricky ;-)
0
 
LVL 92

Expert Comment

by:objects
ID: 11890099
Helps if you read the question :-D
0
 

Expert Comment

by:dsj_shock
ID: 11903309
I have heard about this problem before - on quite a few Nokia phones this is a bug en the MIDP-implementation in the phone-software, which means you cannot solve the problem - when dealing with connections in MIDP, phones from Nokia have several bugs, e.g:

Beneath the HttpConnection a StreamConnection-instance is used. On Nokia Phones using the MIDP-specification, the StreamConnection has a serious bug. The only way to break out of StreamConnection.read() is when data is received. If you call StreamConnection.read() when no data is waiting in the in-buffer, the method blocks until data is received with no chance to interrupt. "That's why you have the StreamConnection.available()-method to tell me how much data the in-buffer contains", but wrong, available() always returns 0, no matter how many data the buffer contains. Also you cannot write to a StreamConnection, when blocked in read().

The bugs mentioned above ahev been seen for other than Nokia phones too, and could be the reason of your problems. Maybe a firmware-update for your mobile phone might help. Which mobile phone are you using?

If a firmware-update does not work, you will have to work yourself around the problem, e.g. by "telling" the server to close the connection...
0
 

Author Comment

by:hawkly
ID: 11909017
To dsj_shock,

1. Any document of the bug on nokia phone?
2. is't the bug just occur in nokia phone? Because currently i'm nokia 6600, nokia 6610, motorola C650 and sony ericsson T610 for testing.
3. How can i do a firmware-update?

thanks
0
 

Author Comment

by:hawkly
ID: 11909025
1 more question, does all the handphone support more than 1 http connection?

thanks
0
 

Accepted Solution

by:
dsj_shock earned 75 total points
ID: 11910617
1.
There are no documentation of these bugs, especially not from the manufacturers them selves. The only documentation are those who ran into the bugs. After I discovered these bugs through my professional work, I ran into this interasting articel:

http://www.russellbeattie.com/notebook/1002646.html

2.
The above articel only applies to Nokia 7650 phones, but I've heard of developers having the same problems with other Nokia phones and a Siemens phone. Regarding the Siemens phone, an update of the firmware helped the problem. If you are expreriencing this problem on all your phones, there still might be a programmatic error, which I don't see by the way.

3.
You go to the store where you bought the phone and asks, if there are any firmware updates available. They check the version of your phone, and gives you a price :-)

4.
No, some handphones only support 1 connection, and sometimes it's hard to find out which ones - the handphone manufactures are NOT good at documenting these kind of things.
0
 

Expert Comment

by:dsj_shock
ID: 11910692
Try if the following code might help:

    void getViaHttpConnection(String url) throws IOException {
         HttpConnection c = null;
         InputStream is = null;
         try {
             c = (HttpConnection)Connector.open(url);
             is = c.openInputStream();
 
             String type = c.getType();
 
             // Get the length and process the data
             int len = (int)c.getLength();
             if (len > 0) {
                 byte[] data = new byte[len];
                 int actual = is.read(data);
                 ...
             } else {
                 int ch;
                 while ((ch = is.read()) != -1) {
                     ...
                 }
             }
         } finally {
             if (is != null)
                 is.close();
             if (c != null)
                 c.close();
         }
     }

Usually when dealing with http-content, you establish a connection, sends a request, receives the response, and closes the connection. Why do you request the server-connection to stay alive after receiving the response by doing this: httpConnection.setRequestProperty("Connection","Keep-Alive");  ??
If there isn't any good reasons why you do this, remove that line of code, and the server will close the connection.
0
 

Expert Comment

by:dsj_shock
ID: 11910740
...or replace

httpConnection.setRequestProperty("Connection","Keep-Alive");

with

httpConnection.setRequestProperty("Connection","close");
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now