5

I often find myself using this idiom:

AtomicReference<MyCoolObject> coolReference = new AtomicReference(new MyCoolObject());

getOptionalValue().ifPresent(presentValue -> {
  coolReference.set(new MyCoolObject(presentValue));
});
return coolReference.get(); 

Is this a bad habit, or a legitimate use of AtomicReference?

6
  • What's the point? Why do you need an atomic reference? Commented Mar 20, 2018 at 22:37
  • What problem are you trying to solve with that construct? Commented Mar 20, 2018 at 22:38
  • FYI, an alternative using method references: getOptionalValue().map(MyCoolObject::new).ifPresent(coolReference::set) Commented Mar 20, 2018 at 22:39
  • 2
    Better return getOptionalValue().map(MyCoolObject::new).orElseGet(MyCoolObject::new); Commented Mar 20, 2018 at 22:41
  • @shmosel, Because I can't return the new MyCoolObject inside the lambda. Commented Mar 21, 2018 at 14:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.