I've a method to write the data in shared preference like,
private static void save(final Context context, final String key, final Object value) {
new Thread(new Runnable() {
@Override
public void run() {
SharedPreferences sharedPref = context.createDeviceProtectedStorageContext().getSharedPreferences(MY_SHARED_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
}
editor.apply();
}
}).start();
}
Android documentation says,
Another consideration in deciding on how many threads to have is that threads aren’t free: they take up memory. Each thread costs a minimum of 64k of memory. This adds up quickly across the many apps installed on a device, especially in situations where the call stacks grow significantly.
it encourages to create a single thread like Handler thread and use it to do background job.
My thought is that save operation might take sometime so planned to have it in background thread but for the following questions i do not have clear answer which is stopping me to do it.
Will the resources allocated for this thread be freed-up when the caller exists this method?
What happens when there are too many calls to this
save
util method? Will thread creation be an overhead?In my case I do not want to have communication with UI thread or neither trying to communicate with another thread. My only purpose is to do a time (not a long running one) consuming tasks in separate thread. Here which one would be better thread creation or Handler or Async task?
Someone please help me understand this.