Skip to content

Data Race between Batch.tryAddFirstEvent and Batch.unlockAndSealIfNeeded #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
van-closed opened this issue Mar 23, 2025 · 0 comments

Comments

@van-closed
Copy link

Short Description

When Emitter.emitAndReturnBatch is called concurrently, it is possible that the thread running Batch.tryAddFirstEvent
gets context switched out after writing the event to buffer and incrementing the event count but
before Batch.firstEventTimeStamp is set. This can cause timeSinceFirstEvent to be inaccurate, leading to the batch not
being sealed within the configured flushMillis.

  private boolean tryAddFirstEvent(byte[] event)
  {
    if (!tryReserveFirstEventSizeAndLock(event)) {
      return false;
    }
    try {
      firstEventLock.writeLock().lock();
      int bufferOffset = emitter.batchingStrategy.writeBatchStart(buffer);
      writeEvent(event, bufferOffset);
      eventCount.incrementAndGet();
      firstEventTimestamp = System.currentTimeMillis();
      return true;
    }
    finally {
      firstEventLock.writeLock().unlock();
      unlock();
    }
  }
  private void unlockAndSealIfNeeded()
  {
    if (eventCount.incrementAndGet() >= emitter.config.getFlushCount()) {
      unlockAndSeal();
    } else {
      firstEventLock.readLock().lock();
      long firstEventTimestampValue = firstEventTimestamp;
      firstEventLock.readLock().unlock();
      long timeSinceFirstEvent = System.currentTimeMillis() - firstEventTimestampValue;
      if (firstEventTimestampValue > 0 && timeSinceFirstEvent > emitter.config.getFlushMillis()) {
        unlockAndSeal();
      } else {
        unlock();
      }
    }
  }

Stack Trace

Stack Trace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant