-
Notifications
You must be signed in to change notification settings - Fork 815
Avoid using ConcurrentDictionary for channels with few methods #2597
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
76d9389
Avoid using ConcurrentDictionary for channels with few methods
JamesNK 739e67f
Update
JamesNK d9b4a3a
Fix build?
JamesNK 8ceb615
Update src/Grpc.Net.Client/Internal/ThreadSafeLookup.cs
JamesNK a3e4a05
PR feedback
JamesNK 485dbda
Fix merge
JamesNK 15a3409
Update src/Grpc.Net.Client/Internal/ThreadSafeLookup.cs
JamesNK File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| #region Copyright notice and license | ||
|
|
||
| // Copyright 2019 The gRPC Authors | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #endregion | ||
|
|
||
| using System.Collections.Concurrent; | ||
|
|
||
| internal sealed class ThreadSafeLookup<TKey, TValue> where TKey : notnull | ||
| { | ||
| // Avoid allocating ConcurrentDictionary until the threshold is reached. | ||
| // Looking up a key in an array is as fast as a dictionary for small collections and uses much less memory. | ||
| internal const int Threshold = 10; | ||
|
|
||
| private KeyValuePair<TKey, TValue>[] _array = Array.Empty<KeyValuePair<TKey, TValue>>(); | ||
| private ConcurrentDictionary<TKey, TValue>? _dictionary; | ||
|
|
||
| /// <summary> | ||
| /// Gets the value for the key if it exists. If the key does not exist then the value is created using the valueFactory. | ||
| /// The value is created outside of a lock and there is no guarentee which value will be stored or returned. | ||
| /// </summary> | ||
| public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory) | ||
| { | ||
| if (_dictionary != null) | ||
| { | ||
| return _dictionary.GetOrAdd(key, valueFactory); | ||
| } | ||
|
|
||
| if (TryGetValue(_array, key, out var value)) | ||
| { | ||
| return value; | ||
| } | ||
|
|
||
| var newValue = valueFactory(key); | ||
|
|
||
| lock (this) | ||
| { | ||
| if (_dictionary != null) | ||
| { | ||
| _dictionary.TryAdd(key, newValue); | ||
| } | ||
| else | ||
| { | ||
| // Double check inside lock if the key was added to the array by another thread. | ||
| if (TryGetValue(_array, key, out value)) | ||
| { | ||
| return value; | ||
| } | ||
|
|
||
| if (_array.Length + 1 > Threshold) | ||
| { | ||
| // Array length exceeds threshold so switch to dictionary. | ||
| var newDict = new ConcurrentDictionary<TKey, TValue>(); | ||
| foreach (var kvp in _array) | ||
| { | ||
| newDict.TryAdd(kvp.Key, kvp.Value); | ||
| } | ||
| newDict.TryAdd(key, newValue); | ||
|
|
||
| _dictionary = newDict; | ||
| _array = Array.Empty<KeyValuePair<TKey, TValue>>(); | ||
| } | ||
| else | ||
| { | ||
| // Add new value by creating a new array with old plus new value. | ||
| var newArray = new KeyValuePair<TKey, TValue>[_array.Length + 1]; | ||
| Array.Copy(_array, newArray, _array.Length); | ||
| newArray[newArray.Length - 1] = new KeyValuePair<TKey, TValue>(key, newValue); | ||
|
|
||
| _array = newArray; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return newValue; | ||
| } | ||
|
|
||
| private static bool TryGetValue(KeyValuePair<TKey, TValue>[] array, TKey key, out TValue value) | ||
| { | ||
| foreach (var kvp in array) | ||
| { | ||
| if (EqualityComparer<TKey>.Default.Equals(kvp.Key, key)) | ||
| { | ||
| value = kvp.Value; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| value = default!; | ||
| return false; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| #region Copyright notice and license | ||
|
|
||
| // Copyright 2019 The gRPC Authors | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #endregion | ||
|
|
||
| namespace Grpc.Net.Client.Tests; | ||
|
|
||
| [TestFixture] | ||
| public class ThreadSafeLookupTests | ||
| { | ||
| [Test] | ||
| public void GetOrAdd_ReturnsCorrectValueForNewKey() | ||
| { | ||
| var lookup = new ThreadSafeLookup<int, string>(); | ||
| var result = lookup.GetOrAdd(1, k => "Value-1"); | ||
|
|
||
| Assert.AreEqual("Value-1", result); | ||
| } | ||
|
|
||
| [Test] | ||
| public void GetOrAdd_ReturnsExistingValueForExistingKey() | ||
| { | ||
| var lookup = new ThreadSafeLookup<int, string>(); | ||
| lookup.GetOrAdd(1, k => "InitialValue"); | ||
| var result = lookup.GetOrAdd(1, k => "NewValue"); | ||
|
|
||
| Assert.AreEqual("InitialValue", result); | ||
| } | ||
|
|
||
| [Test] | ||
| public void GetOrAdd_SwitchesToDictionaryAfterThreshold() | ||
| { | ||
| var addCount = (ThreadSafeLookup<int, string>.Threshold * 2); | ||
| var lookup = new ThreadSafeLookup<int, string>(); | ||
|
|
||
| for (var i = 0; i <= addCount; i++) | ||
| { | ||
| lookup.GetOrAdd(i, k => $"Value-{k}"); | ||
| } | ||
|
|
||
| var result = lookup.GetOrAdd(addCount, k => $"NewValue-{addCount}"); | ||
|
|
||
| Assert.AreEqual($"Value-{addCount}", result); | ||
| } | ||
|
|
||
| [Test] | ||
| public void GetOrAdd_HandlesConcurrentAccess() | ||
| { | ||
| var lookup = new ThreadSafeLookup<int, string>(); | ||
| Parallel.For(0, 1000, i => | ||
| { | ||
| var value = lookup.GetOrAdd(i, k => $"Value-{k}"); | ||
| Assert.AreEqual($"Value-{i}", value); | ||
| }); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.