Search code examples
javaandroidorg.json

Why am I getting Concurrent Thread Error


Actually I'm sending an arraylist of base64 string to server by socket.io.But I don't know why I'm getting this strange error .

I thought it's important to post the base64 conversion method that's why I've posted that as well.

Can anyone please help me to fix this error?

Error:

java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:792)
    at java.util.HashMap$EntryIterator.next(HashMap.java:829)
    at java.util.HashMap$EntryIterator.next(HashMap.java:827)
    at org.json.JSONObject.writeTo(JSONObject.java:666)
    at org.json.JSONStringer.value(JSONStringer.java:237)
    at org.json.JSONArray.writeTo(JSONArray.java:572)
    at org.json.JSONArray.toString(JSONArray.java:544)
    at java.lang.StringBuilder.append(StringBuilder.java:202)
    at io.socket.parser.Parser$Encoder.encodeAsString(Parser.java:116)
    at io.socket.parser.Parser$Encoder.encode(Parser.java:85)
    at io.socket.client.Manager.packet(Manager.java:461)
    at io.socket.client.Socket.packet(Socket.java:264)
    at io.socket.client.Socket.access$1100(Socket.java:19)
    at io.socket.client.Socket$5.run(Socket.java:201)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    at java.lang.Thread.run(Thread.java:856)

Code:

// Here bit is the bitmap arraylist
final JSONObject obj=new JSONObject();
try {
    obj.put("uploads_username",username);
    obj.put("uploads",convert(bit));
    socket.emit("data",obj);
   } catch (JSONException e) {
    e.printStackTrace();
}

public ArrayList<String> convert(ArrayList<Bitmap> bitmap){
    ArrayList<String> pics=new ArrayList<>();
    for(int i=0;i<bitmap.size();i++){
        pics.add(getStringImage(bitmap.get(i)));
    }

    return pics;
}

public static String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

    return encodedImage;
}

Solution

  • It's possible that elsewhere in your code you are manipulating the object passed to socket.io (or one of its fields) concurrently while the asynchronous network call is being performed.

    Can you isolate the code being executed to only contain the creation of the object and the network call and see if the error still happens?