Skip to content

Commit 76b129a

Browse files
committed
fix: Resolve race condition in concurrent Transaction initialization
Implement a double-checked locking pattern in and methods. When multiple threads attempt to use a lazy transaction simultaneously, they race to acquire the lock. Previously, losing threads would acquire the lock and blindly send another 'begin transaction' request, ignoring that the winner had already initialized the transaction ID. This change ensures that threads re-check after acquiring the lock. If the ID is present, they skip the initialization request and use the established ID.
1 parent 133ead1 commit 76b129a

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

google/cloud/spanner_v1/snapshot.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,10 @@ def _get_streamed_result_set(
638638
if self._transaction_id is None:
639639
is_inline_begin = True
640640
self._lock.acquire()
641+
if self._transaction_id is not None:
642+
is_inline_begin = False
643+
self._lock.release()
644+
request.transaction = TransactionSelector(id=self._transaction_id)
641645

642646
iterator = _restart_on_unavailable(
643647
method=method,

google/cloud/spanner_v1/transaction.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,9 @@ def execute_update(
512512
if self._transaction_id is None:
513513
is_inline_begin = True
514514
self._lock.acquire()
515+
if self._transaction_id is not None:
516+
is_inline_begin = False
517+
self._lock.release()
515518

516519
execute_sql_request = ExecuteSqlRequest(
517520
session=session.name,
@@ -670,6 +673,9 @@ def batch_update(
670673
if self._transaction_id is None:
671674
is_inline_begin = True
672675
self._lock.acquire()
676+
if self._transaction_id is not None:
677+
is_inline_begin = False
678+
self._lock.release()
673679

674680
execute_batch_dml_request = ExecuteBatchDmlRequest(
675681
session=session.name,

0 commit comments

Comments
 (0)