Skip to content

This is not thread-safe. #2

@creswick

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.

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