22
33using System ;
44using System . Collections . Concurrent ;
5+ using System . Threading ;
56
67namespace Java . Interop
78{
@@ -39,12 +40,12 @@ internal JniType JniPeerType {
3940
4041 readonly Type DeclaringType ;
4142
42- readonly ConcurrentDictionary < string , JniMethodInfo > InstanceMethods = new ConcurrentDictionary < string , JniMethodInfo > ( 1 , 3 , StringComparer . Ordinal ) ;
43+ ConcurrentDictionary < string , JniMethodInfo > ? InstanceMethods ;
4344 readonly ConcurrentDictionary < Type , JniInstanceMethods > SubclassConstructors = new ConcurrentDictionary < Type , JniInstanceMethods > ( 1 , 1 ) ;
4445
4546 internal void Dispose ( )
4647 {
47- InstanceMethods . Clear ( ) ;
48+ Interlocked . Exchange ( ref InstanceMethods , null ) ? . Clear ( ) ;
4849 foreach ( var p in SubclassConstructors . Values )
4950 p . Dispose ( ) ;
5051 SubclassConstructors . Clear ( ) ;
@@ -58,7 +59,7 @@ public JniMethodInfo GetConstructor (string signature)
5859 {
5960 if ( signature == null )
6061 throw new ArgumentNullException ( nameof ( signature ) ) ;
61- return InstanceMethods . GetOrAdd ( signature , static ( member , methods ) =>
62+ return GetInstanceMethods ( ) . GetOrAdd ( signature , static ( member , methods ) =>
6263 methods . JniPeerType . GetConstructor ( member ) , this ) ;
6364 }
6465
@@ -94,13 +95,23 @@ internal JniInstanceMethods GetConstructorsForType (Type declaringType)
9495
9596 public JniMethodInfo GetMethodInfo ( string encodedMember )
9697 {
97- return InstanceMethods . GetOrAdd ( encodedMember , static ( member , methods ) => {
98+ return GetInstanceMethods ( ) . GetOrAdd ( encodedMember , static ( member , methods ) => {
9899 string method , signature ;
99100 JniPeerMembers . GetNameAndSignature ( member , out method , out signature ) ;
100101 return methods . GetMethodInfo ( method , signature ) ;
101102 } , this ) ;
102103 }
103104
105+ ConcurrentDictionary < string , JniMethodInfo > GetInstanceMethods ( )
106+ {
107+ var methods = Volatile . Read ( ref InstanceMethods ) ;
108+ if ( methods != null )
109+ return methods ;
110+
111+ var candidate = new ConcurrentDictionary < string , JniMethodInfo > ( 1 , 3 , StringComparer . Ordinal ) ;
112+ return Interlocked . CompareExchange ( ref InstanceMethods , candidate , null ) ?? candidate ;
113+ }
114+
104115 JniMethodInfo GetMethodInfo ( string method , string signature )
105116 {
106117 var m = ( JniMethodInfo ? ) null ;
0 commit comments