tags:

views:

108

answers:

3

Hi,

I am facing a problem with a stopping thread which is in a synchronized block. I am using TCP socket. The problem is that I am waiting on a DataInputStream object and I want to create a new socket again but it doesn't allow me to do because of the synchronized block.

I have tried with Thread.interrupted(). I cannot avoid the synchronized block. Is there any other way to do the same?

dis = new DataInputStream(ReadWriteData.kkSocket.getInputStream());
int i = -1;
String aval = ""; //new String();
char c = (char)dis.read();

It is getting blocked on dis.read().

What I should do for escaping the dis.read when I want to create a new socket?

Thanks in advance.

+1  A: 

You could always check if there is data available to read, by calling dis.available() to determine the number of bytes that can be read without blocking.

Using some additional logic could then allow for the creation of the new socket.

gpampara
+1  A: 

You could close the stream and catch it that way, but that may not always be the best option.

Kristopher Ives
I believe this is the recommended way to do this.
James
A: 

If you know how many streams you want to have you can do something like:

private static final int N_STREAMS = 3;
...
InputStream[] streams = new InputStream[N_STREAMS];
List<StringBuilder> outputBuilders = new ArrayList<StringBuilder>();
for (int i=0; i < N_STREAMS; i++) {
  // A StringBuilder for every stream
  outputBuilder.append(new StringBuilder());
  try {        
    streams[i] = new DataInputStream(ReadWriteData.kkSocket.getInputStream());
  } catch (IOException e) {
    // Propagate error or ignore?
  }
}

// Read data
for (int i=0; i < N_STREAMS; i++) {
  InputStream currentStream = streams[i];
  StringBuilder currentBuilder = outputBuilders.get(i);
  if (currentStream != null && currentStream.available() > 0) {
    try {
      currentBuilder.append(stream.read());
    } catch (IOException e) {
      // Do something
    }
  }
  if (currentStream != null && currentStream??? == EOF) {
    // I don't know how to detect EOF on this stream...
    try {
      streams[i] = null; // Mark it as closed
      currentStream.close();
    } catch (...) {
      // Do something
    }
  }
}
// You know have a StringBuilder per socket; do with it what you want

As you might have noticed I don't know anything about Android. But this seems generic enough to fit your usage, or at least provide a hint.

extraneon