Skip to content

This is not thread-safe. #2

Description

@creswick
  public long next() {
    // This needs to be inside the synchronized block:
    long currentTime = System.currentTimeMillis();

Without that change, two threads (call them thread-a and thread-b) call next();

  • Thread-a gets time t
  • Thread-b gets time t+1
  • Thread-a is interrupted for some reason (due to cpu scheduling, for example)
  • Thread-b enters the synchronized block; and sets referenceTime to to time t+1.
  • Thread-a blocks on synchronized block.
  • Thread-b exits the block, relinquishing the lock.
  • Thread-a enters the synchronized block, and compares it's currentTime (t) with the referenceTime (t+1), and throws a RuntimeException.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions