Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

[shared_preferences] Fix concurrent modification of the shared preferences on Android #3684

Merged
merged 4 commits into from
Mar 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/shared_preferences/shared_preferences/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 2.0.4

* Fix a regression with simultaneous writes on Android.

## 2.0.3

* Android: don't create additional Handler when method channel is called.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -53,7 +53,7 @@ class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {
MethodCallHandlerImpl(Context context) {
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
executor =
new ThreadPoolExecutor(0, 1, 30L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
new ThreadPoolExecutor(0, 1, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
handler = new Handler(Looper.getMainLooper());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,18 @@ void main() {
expect(preferences.getDouble('double'), null);
expect(preferences.getStringList('List'), null);
});

testWidgets('simultaneous writes', (WidgetTester _) async {
final List<Future<bool>> writes = <Future<bool>>[];
final int writeCount = 100;
for (int i = 1; i <= writeCount; i++) {
writes.add(preferences.setInt('int', i));
}
List<bool> result = await Future.wait(writes, eagerError: true);
// All writes should succeed.
expect(result.where((element) => !element), isEmpty);
// The last write should win.
expect(preferences.getInt('int'), writeCount);
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: shared_preferences
description: Flutter plugin for reading and writing simple key-value pairs.
Wraps NSUserDefaults on iOS and SharedPreferences on Android.
homepage: https://github.com/flutter/plugins/tree/master/packages/shared_preferences/shared_preferences
version: 2.0.3
version: 2.0.4

flutter:
plugin:
Expand Down