ConcurrentModificationException的

时间:2013-07-10 10:01:29

标签: java android android-asynctask thread-safety

以下方法是从AsyncTask中的各个地方调用的。它是为Android编码的。获取ConcurrentModificationException。如何使这个方法线程安全

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



                      ........
                      ........

2 个答案:

答案 0 :(得分:0)

你可以这样做:

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
                 //...

答案 1 :(得分:0)

synchronized上制作代码data

synchronized(data) {
    try {
        printWriter = new BufferedWriter(new FileWriter(file), 8192);
        // ...
    }
}