Developer87
Developer87

Reputation: 2708

Correct put operation to work well in concurrent env?

Will that work properly (no race conditions) in concurrent environment?

This is kind of "key autoincrement" feature implementation..

private final AtomicInteger atomic = new AtomicInteger(0);
private Map<Long, Integer> hashmap = new ConcurrentHashMap<>();

void put(String value) {
   hashmap.put(atomic.getAndIncrement(), Integer.valueOf(value));
}

I guess not, because Integer.valueOf isn't synchronized.. Thanks!

Upvotes: 1

Views: 34

Answers (1)

LppEdd
LppEdd

Reputation: 21144

There is nothing to synchronize here

Integer.valueOf(value)

The value argument is a String and that means it is copied (not really, but consider it to be so).
A String is also immutable.

valueOf is a pure function which doesn't hold a state. Thus, it is by definition thread-safe.
Looking at this small snippet, your code seems fine.

Upvotes: 1

Related Questions