@@ -163,11 +163,22 @@ internal Task<ManagedSession> AcquireManagedSessionAsync(SpannerClientCreationOp
163163 {
164164 SessionPoolSegmentKey segmentKey = SessionPoolSegmentKey . Create ( dbName ) . WithDatabaseRole ( dbRole ) ;
165165 GaxPreconditions . CheckNotNull ( options , nameof ( options ) ) ;
166+ Lazy < Task < ManagedSession > > lazyManagedSessionTask ;
166167
167- // To work around nuances of how value factory execution works in a concurrent dictionary
168- // We need to wrap the call to CreateMultiplexSessionAsync() in a LazyTask
169- // to avoid concurrent threads spinning off multiple executions of CreateMultiplexSessionAsync()
170- var lazyManagedSessionTask = _targetedSessions . GetOrAdd ( ( options , segmentKey ) , _ => new Lazy < Task < ManagedSession > > ( CreateMultiplexSessionAsync , LazyThreadSafetyMode . ExecutionAndPublication ) ) ;
168+ if ( ! string . IsNullOrEmpty ( Environment . GetEnvironmentVariable ( "SPANNER_EMULATOR_HOST" ) ) && _targetedSessions . ContainsKey ( ( options , segmentKey ) ) )
169+ {
170+ // The Spanner Emulator has a limitation that it does not support concurrent transactions on a single multiplex session.
171+ // To make sure async integration tests (which basically mimic concurrent transactions) work, we need to create a new session instance each time
172+ lazyManagedSessionTask = _targetedSessions [ ( options , segmentKey ) ] = new Lazy < Task < ManagedSession > > ( CreateMultiplexSessionAsync , LazyThreadSafetyMode . ExecutionAndPublication ) ;
173+ }
174+ else
175+ {
176+ // To work around nuances of how value factory execution works in a concurrent dictionary
177+ // We need to wrap the call to CreateMultiplexSessionAsync() in a LazyTask
178+ // to avoid concurrent threads spinning off multiple executions of CreateMultiplexSessionAsync()
179+ lazyManagedSessionTask = _targetedSessions . GetOrAdd ( ( options , segmentKey ) , _ => new Lazy < Task < ManagedSession > > ( CreateMultiplexSessionAsync , LazyThreadSafetyMode . ExecutionAndPublication ) ) ;
180+
181+ }
171182
172183 return lazyManagedSessionTask . Value ;
173184
0 commit comments