Android SharedPreferences Concurrency

I write a date in SharedPreferences when ever my application retrieves the latest data from a feed. Now I need to read this value, but I can not find much information about concurrency when reading / writing in SharedPreferences.

Should I use a synchronized keyword in my methods to prevent / reduce the chances of forced closure? Or did people at Google make SharedPreferences in a way that I didn't worry about?

For the record, I donโ€™t think there is a high chance of a collision due to the rare read and write operations, although I would not like to assume that everything will โ€œworkโ€.

+4
source share
2 answers

When opening SharedPreferences, use the MODE_MULTI_PROCESS flag. This was a legacy (but undocumented) behavior in and before Gingerbread (Android 2.3), and this flag is implied when targeting such releases. For applications targeting SDK versions larger than Android 2.3, this flag should be explicitly set as desired.

This constant was deprecated at API level 23.
MODE_MULTI_PROCESS does not work reliably in some versions of Android and, in addition, does not provide any mechanism for coordinating simultaneous changes between processes. Applications should not attempt to use it. Instead, they should use an explicit cross-data management process, such as ContentProvider .

+3
source

Like android doc .

Note. This class currently does not support the use of multiple processes. This will be added later.

So, if you are concerned about multi-threaded access to general settings, you need to synchronize.

+1
source

Source: https://habr.com/ru/post/1396423/


All Articles