Thread stopping in synchronized block

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.


Asked by: Ryan903 | Posted: 25-01-2022






Answer 1

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.

Answered by: Adelaide372 | Posted: 26-02-2022



Answer 2

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

Answered by: Lucas280 | Posted: 26-02-2022



Answer 3

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.

Answered by: Ted279 | Posted: 26-02-2022



Similar questions

java - mHandler isn't set from within a synchronized block in Android SDK

Looking through the Android SDK framework source code, I've come across this: private final class GpsLocationProviderThread extends Thread { public GpsLocationProviderThread() { super("GpsLocationProvider"); } public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); initialize(); Looper.prepare(); ...


gridview - Android: Synchronized scrolling of two different views

I have a tricky problem related to synchronized scrolling of two different views. I've made my own custom grid view widget, which has "sticky" views to the left and top that only in one direction with the grid. Think of a calendar where you have times at the top, dates at the left, and when you scroll horizontally through time, the date view should stay put, and when you scroll vertically through the dates, the time view s...


java - Does the android.os.Handler class eliminate the need to declare certain methods as synchronized?

In putting together a simple "Clock" application I discovered that Android requires you to use android.os.Handler that lives in Thread A in order to update View objects in Thread A with the results of data that come from Thread B. I'm still relatively new to Java, and this is the first time I've dealt explicitly with Threads before, but I know that ordinarily you'd declare methods and/or operations as synchronized ...


android - How to do a blocking and synchronized activity?

Well, please don't ask me why, but I need to start a synchronous and blocking activity so that the program flow won't continue until it's finished. I know how to do a synchronous Dialog, but how can I do a synchronous activity? Following are two approaches I tried but failed: // In the 1st activity, start the 2nd activity in the usual way startActivity(intent); Looper.loop(); // but pause the...


java - Misuse of synchronized?

I'm trying to synchronize two blocks of code for an Android app. The first block uses an AsyncFacebookRunner to make a request for a user's interests, if any. If interests were found, a member variable for that user is populated with their interests from the Facebook JSON response. The second code block checks if the user actually has interests by looking at that member variable. If there are inter...


synchronized methods in Android Activities

I have two activities. In activity 1 I write a value to a SQLite database by entering that value into an EditText field. Once I press the submit button, the data is written and I am moved along to another activity - activity 2. Activity2 also does the same thing in that I can write new data and persist it to the database with a button click. So, my question is: do I need to synchronize the method (which is on a separat...


java - Need help with Synchronized

I am creating a live streaming app, but I'm stuck at a certain point. So, this is my code: public synchronized byte[] getPicture(int Width, int Height) { FrameWidth = Width; FrameHeight = Height; try { while (!isPreviewOn) { wait(); } isDecoding = true; mAvailableFrame = false; c.setOneShotPreviewCallback(mPreviewC...


android - Trade off with declaring method synchronized in java?

I had a problem with a thread locking up for some still unknown reason in my Android App whenever I tried to kill Thread B from Thread A (usually, sometimes it worked). I guessed that it was because some of my methods were making calls across the threads without being synchronized. I made the cancel method and a lot of methods that were essentially event handlers synchronized and made a few shared variables volatile and ...


java - How to correctly use synchronized?

This piece of code: synchronized (mList) { if (mList.size() != 0) { int s = mList.size() - 1; for (int i = s; i &gt; 0; i -= OFFSET) { mList.get(i).doDraw(canv); } getHead().drawHead(canv); } } Randomly throws AIOOBEs. From what I've read, the synchronized should prevent that, so what am I doing wrong? Edits: AIOOBE = Arra...


java - How to pass the email id that to be synchronized into create event calendar in android?

How to pass the mail id of the calendar that to be synchronized into the create event through email? I have a spinner that shows the list of accounts to be synchronized as below picture. Now, as usual passing title,description to create event in calendar application, i use following code. ContentValues values = new ContentValues(); values.put("calendar_id", 1); values.put("title", title1); value...






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top