Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent for Guava Striped-Class in C#?

There are some cases where I really like using Guava's Striped class.

Is there an equivalent in C#?

like image 388
Fabian Barney Avatar asked Aug 17 '15 09:08

Fabian Barney


2 Answers

It doesn't look like there is a direct equivalent, but there are some lockless thread-safe collection options (I'm not sure what you're trying to achieve, so I can't say if they will work for your scenario). Have a look at the System.Collections.Concurrent Namespace.

In particular, ConcurrentBag, ConcurrentQueue, ConcurrentStack, and ConcurrentDictionary all have different locking/lockless thread-safe strategies. Some are explained in this blog post.

You might be able to get what you want via the Partitioner class, although I am unsure of the implementation.

@Behrooz is incorrect in saying that all .net framework types only use a single lock for the entire list. Take a look at the source for ConcurrentDictionary. Line 71 suggests that this class is implemented using multiple locks.

If you really want to, you could write your own version. The source for the Guava Striped is: https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/Striped.java

like image 119
Zachary Yates Avatar answered Nov 02 '22 01:11

Zachary Yates


I think best you can do is implementing your own because all dotnet framework types offer only one lock for the entire list.
To do that you can use the GetHashCode() function, modulus(%) it with the number of stripes you want. and use it as an index for Tuple<TLock, List<T>>[] where TLock can be any kind of lock defined in System.Threading namespace and T is the type you want to store/access.
With this you can decide how you want your stripes to be stored. There are choices like HashSet(inefficient in your case since you already use some of the bits to calculate the stripe index), SortedSet, List, Array.

btw, Thank you for the question, It's gonna help me solve a problem I'm having.

like image 6
Behrooz Avatar answered Nov 02 '22 02:11

Behrooz