is.magl
is.magl

Reputation: 325

Is this a correct use case for AtomicReference in Java?

I have a processor cache class which is a singleton and has a Processor field. The Processor field will be set by a single Updating thread and used by many Worker threads.

I don't know whether my current implementation is a appropriate usage of the AtomicReference. Would you please check and correct it? In addition, can I just use the volatile instead of the AtomicReference in this case?

The implementation:

class Cache {
    private AtomicReference<Processor> processor;

    public static getInstance() { ... }

    public Processor getProcessor() {
        return processor.get();
    }

    public void setProcessor(Processor old, Processor new) {
        processor.compareAndSet(old, new);
    }
}

/* Only one thread will update the processor cache */
class UpdatingThread {
    private Processor oldProcessor;

    public void run() {
        // some logic
        Processor newProcessor = createNewProcessor();
        Cache.getInstance().setProcessor(oldProcessor, newProcessor);
        oldProcessor = newProcessor;
        // some more logic
    }
}

/* Multiple workers will use the processor */
class WorderThread {
    public void run() {
        // some logic
        Processor processor = Cache.getInstance().getProcessor();
        // more logic using the processor
    }
}

Upvotes: 1

Views: 435

Answers (1)

K Erlandsson
K Erlandsson

Reputation: 13696

Since the only thing you actually do is re-assign the processor field in the Cache class, a volatile field would be better suited. You do not use the extra features the AtomicReference provides.

Besides, if you do want to use AtomReference you should just use the set method so that you don't have to keep track of the oldProcessor.

Upvotes: 3

Related Questions