Skip to content
This repository was archived by the owner on Jul 28, 2020. It is now read-only.
This repository was archived by the owner on Jul 28, 2020. It is now read-only.

safeCounter() is not thread-safe. #4

@ohyoung79

Description

@ohyoung79

The current implementation of safeCounter() seems not to be thread-safe. "counter = counter <DISCRETE? counter: 0" and "return counter ++" are likely to work separately. "return counter ++" itself is not thread-safe either. The Orignal program is written in a javascript language that works only in single-thread, it is thread-safe by default. But the java program must be implemented thread-safe. The simplest is to safecounter() synchronized, and if you want to implement lock-free, you'll have to fix it like this:

private static int counter = 0; ==>
private static AtomicInteger counter = new AtomicInteger (0);

private static int safeCounter () {
    counter = counter <DISCRETE_VALUES? counter: 0;
    return counter ++;
} ==>
private static int safeCounter () {
    int oldVal = 0;
    int newVal = 0;
    for (;;) {
        oldVal = counter.get ();
        newVal = oldVal < DISCRETE_VALUES ? oldVal : 0;
        newVal ++;
        if (counter.compareAndSet (oldVal, newVal)) return newVal - 1;
    }
}

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