jiduvah
jiduvah

Reputation: 5168

Synchronised Keyword

I am developing an app which downloads images and saves them to the sdcard. The class which interacts with the sdcard looks like this...

public class SDCardImageManagerImp implements SDCardImageManager {

    private Context context;

    @Inject
    public SDCardImageManagerImp(Context context) {
        this.context = context;
    }

    @Override
    public void saveToSDCard(String id, Bitmap bitmap) throws FileNotFoundException {
        FileOutputStream outputStream = context.openFileOutput(id, Context.MODE_PRIVATE);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
    }

    @Override
    public Bitmap getImage(String id) throws FileNotFoundException {
        return BitmapFactory.decodeStream(context.openFileInput(id));
    }

    @Override
    public void deleteImage(String id) {
        context.deleteFile(id);
    }

}

This class is a singleton as I read writing to a disk with multiple threads can hinder performance. However I do have multiple threads downloading the data and sending it to this class. So my questions is should all of the methods in this class have the syncronized key work on them?

Upvotes: 2

Views: 138

Answers (2)

stuckless
stuckless

Reputation: 6545

Why not create a Thread Pool of Image Writers using the writerThreadPool = Executors.newFixedThreadPool(numThreads). This way, you call writerThreadPool.submit() allowing the image to be queued up for writing as a thread becomes available. The Thread Pool will handle the io throttling for you, since it will only ever allow the given number of threads that you create. And by using the Executors.newFixedThreadPool, you can easily play with the number of threads by changing numThreads to allow more or less threads to get the desired performance.

Upvotes: 2

Thilo
Thilo

Reputation: 262794

I don't know if the assumption is valid (that you should throttle I/O to the SD card), but even if it is, you probably want to make this configurable, which the synchronized keyword will not let you.

How about something like a counting Semaphore (and a configuration file to set the number of permits)?

Upvotes: 1

Related Questions