Created
August 28, 2012 17:59
-
-
Save mennankara/3501446 to your computer and use it in GitHub Desktop.
Solution for http://stackoverflow.com/questions/12163125/is-locking-necessary-in-this-concurrentdictionary-caching-scenario
This file contains 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
using System; | |
using System.Collections.Concurrent; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace GeneralTests | |
{ | |
internal class Program | |
{ | |
public class SomeClass | |
{ | |
private static readonly ConcurrentDictionary<int, Lazy<PrivateClass>> SomeClasses = | |
new ConcurrentDictionary<int, Lazy<PrivateClass>>(); | |
private readonly PrivateClass _privateClass; | |
public SomeClass(int cachedInstanceId) | |
{ | |
_privateClass = SomeClasses.GetOrAdd(cachedInstanceId, (key) => new Lazy<PrivateClass>()).Value; | |
} | |
public int SomeCalculationResult() | |
{ | |
return _privateClass.CalculateSomething(); | |
} | |
private class PrivateClass | |
{ | |
public PrivateClass() | |
{ | |
Thread.Sleep(10000); | |
Console.WriteLine("CONSTUCTOR"); | |
} | |
internal int CalculateSomething() | |
{ | |
Console.WriteLine("CALCULATOR"); | |
return 10; | |
} | |
} | |
} | |
private static void Main(string[] args) | |
{ | |
var tasks = new Task[Environment.ProcessorCount]; | |
for (int i = 0; i < Environment.ProcessorCount; i++) | |
{ | |
tasks[i] = Task.Factory.StartNew(() => | |
{ | |
new SomeClass(1).SomeCalculationResult(); | |
}); | |
} | |
Task.WaitAll(tasks); | |
Console.WriteLine("Sleeping a bit"); | |
Thread.Sleep(2000); | |
new SomeClass(1).SomeCalculationResult(); | |
// Output: | |
// CONSTUCTOR | |
// CALCULATOR | |
// CALCULATOR | |
// CALCULATOR | |
// CALCULATOR | |
// Sleeping a bit | |
// CALCULATOR | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment