-1

The below method is being called from various place in AsynTask. It is coded for Android. Getting ConcurrentModificationException. How to make this method thread safe

public static String saveJsonFile(File dir, String name, JSONObject data) {
        final File file = new File(dir.getPath() + File.separator + name);
        try {
            file.createNewFile();
        } catch (final IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedWriter printWriter = null;

        try {
            printWriter = new BufferedWriter(new FileWriter(file), 8192);
            // printWriter = new PrintWriter(file);
            if (data != null)
                data.write(printWriter); // java.util.ConcurrentModificationException



                      ........
                      ........
Vinayak Bevinakatti
  • 40,205
  • 25
  • 108
  • 139
  • 1
    Where is JSONObject.write()? I didn't get at http://developer.android.com/reference/org/json/JSONObject.html – Pankaj Kumar Jul 10 '13 at 10:04
  • It is a custom method added to write data to file. I dont have access to it now its compiled as Jar. Actually it is org.json.douglascrockford.JSONObject – Vinayak Bevinakatti Jul 10 '13 at 10:46
  • @Vinayak.B There are two flavors of methods (other then constructor) in that class that mutate an underlying map. Do you ever invoke `put` or `popuplate` on the JSONObject? – John Vint Jul 10 '13 at 15:11
  • 1
    Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Raedwald Mar 28 '16 at 14:43

2 Answers2

0

You could do something like this:

private final Object lock = new Object();

public static String saveJsonFile(File dir, String name, JSONObject data) {
    final File file = new File(dir.getPath() + File.separator + name);
    try {
        file.createNewFile();
    } catch (final IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    BufferedWriter printWriter = null;

    try {
        printWriter = new BufferedWriter(new FileWriter(file), 8192);

        synchronized(lock) {
            if (data != null)
                 data.write(printWriter); // java.util.ConcurrentModificationException
                 //...
Nicholas
  • 2,147
  • 3
  • 23
  • 31
0

Make your code synchronized on data:

synchronized(data) {
    try {
        printWriter = new BufferedWriter(new FileWriter(file), 8192);
        // ...
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118