简体   繁体   中英

Synchronization and/or mutual exclusion for storage class in services

I need to concurrently read and write a common file with different jobIntentServices in my APP. One service (producer) writes data in the file, while another service (consumer) checks if there is data in the shared file. If there is data, it sends it and, if the data transfer was successful, it deletes the file. I have created the following storage controller class:

public class Storage {
private static final String TAG = "Storage";

public void writeToFile(String filePath, String data, Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e(TAG, "File write failed: " + e.toString());
    }
}

public String readFromFile(String filePath, Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(filePath);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Can not read file: " + e.toString());
    }

    return ret;
}

public boolean fileExists(String filename, Context context) {
    File file = context.getFileStreamPath(filename);
    if(file == null || !file.exists()) {
        return false;
    }
    return true;
}

public boolean deleteFile(String filename, Context context){
    File file = context.getFileStreamPath(filename);
    return file.delete();
}

The class isn't singleton.

I solved it with a singleton class and using locks:

Lock lockDeviceData = new ReentrantLock();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM