Skip to content

Commit 5d14a90

Browse files
authored
Use the ConcurrentDictionary in the CachingExpressionCompiler implementation (#92)
1 parent 8d52609 commit 5d14a90

File tree

1 file changed

+16
-24
lines changed

1 file changed

+16
-24
lines changed

Orm/Xtensive.Orm/Linq/Internals/CachingExpressionCompiler.cs

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,40 @@
1-
// Copyright (C) 2003-2010 Xtensive LLC.
2-
// All rights reserved.
3-
// For conditions of distribution and use, see license.
1+
// Copyright (C) 2009-2020 Xtensive LLC.
2+
// This code is distributed under MIT license terms.
3+
// See the License.txt file in the project root for more information.
44
// Created by: Denis Krjuchkov
55
// Created: 2009.05.06
66

77
using System;
8+
using System.Collections.Concurrent;
89
using System.Linq.Expressions;
9-
using Xtensive.Collections;
1010
using Xtensive.Core;
1111

12-
1312
namespace Xtensive.Linq
1413
{
1514
internal sealed class CachingExpressionCompiler
1615
{
17-
private static readonly object _lock = new object();
18-
private static volatile CachingExpressionCompiler instance;
19-
20-
public static CachingExpressionCompiler Instance {
21-
get {
22-
if (instance==null) lock (_lock) if (instance==null)
23-
instance = new CachingExpressionCompiler();
24-
return instance;
25-
}
26-
}
16+
public static CachingExpressionCompiler Instance { get; } = new CachingExpressionCompiler();
17+
18+
private readonly ConcurrentDictionary<ExpressionTree, Delegate> cache =
19+
new ConcurrentDictionary<ExpressionTree, Delegate>();
20+
21+
private static readonly Func<ExpressionTree, Delegate> expressionTreeCompiler = CompileExpressionTree;
2722

28-
private readonly ThreadSafeDictionary<ExpressionTree, Delegate> cache =
29-
ThreadSafeDictionary<ExpressionTree, Delegate>.Create(new object());
23+
private static Delegate CompileExpressionTree(ExpressionTree tree) =>
24+
((LambdaExpression) tree.ToExpression()).Compile();
3025

3126
public Pair<Delegate, object[]> Compile(LambdaExpression lambda)
3227
{
3328
var constantExtractor = new ConstantExtractor(lambda);
34-
var tree = constantExtractor.Process().ToExpressionTree();
29+
var expressionTree = constantExtractor.Process().ToExpressionTree();
3530
var constants = constantExtractor.GetConstants();
36-
var compiled = cache.GetValue(tree, _tree => ((LambdaExpression) _tree.ToExpression()).Compile());
37-
// var compiled = ((LambdaExpression) tree.ToExpression()).Compile();
31+
32+
var compiled = cache.GetOrAdd(expressionTree, expressionTreeCompiler);
3833
return new Pair<Delegate, object[]>(compiled, constants);
3934
}
4035

4136
// For testing only
42-
public void ClearCache()
43-
{
44-
cache.Clear();
45-
}
37+
public void ClearCache() => cache.Clear();
4638

4739

4840
// Constructors

0 commit comments

Comments
 (0)