[ 
https://issues.apache.org/jira/browse/LUCENE-9001?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16948066#comment-16948066
 ] 

Przemko Robakowski commented on LUCENE-9001:
--------------------------------------------

But you have to ensure that set will be called only once, right? So if you have 
multithreaded code you have to use something like
{code:java}
if (setOnce.get() == null) {
  synchronized(setOnce){
    if(setOnce.get() == null){
      setOnce.set(load());
    }
  }
}
return setOnce.get();
{code}
If you want to skip synchronization and load method is lightweight you could do 
something like this (you can't use this idiom now due to mentioned race 
condition):
{code:java}
if (setOnce.get() == null) {
  try {
    setOnce.set(load());
  } catch (AlreadySetException ignored){
  }
}
return
{code}
It's easier to to understand in my opinion and easier to get it right - no 
double checking of null and no chance that someone will forget/will refactor 
away synchronized keyword. With trySet it's even cleaner:
{code:java}
if (setOnce.get() == null) {
  setOnce.trySet(load());
}
return setOnce.get();
{code}
Sure, I can replace it with AtomicReference.compareAndSet but AtomicReference 
doesn't give you protection and guarantee that object will be set at most once 
(it's easy to introduce atomicRef.set instead by mistake).

I see set/trySet similar to add/offer pair in JDK's Queue - one throwing, one 
returning boolean indicator.

> Race condition in SetOnce
> -------------------------
>
>                 Key: LUCENE-9001
>                 URL: https://issues.apache.org/jira/browse/LUCENE-9001
>             Project: Lucene - Core
>          Issue Type: Bug
>            Reporter: Przemko Robakowski
>            Priority: Minor
>          Time Spent: 10m
>  Remaining Estimate: 0h
>
> There is race condition in SetOnce that can cause code below fail with 
> NullPointerException:
> {code:java}
> SetOnce<String> setOnce = new SetOnce<>();
> new Thread(() -> setOnce.set("thread")).start();
> try{
>     setOnce.set("main");
> } catch (SetOnce.AlreadySetException e){
>     setOnce.get().hashCode(); //possible NPE!
> }
> {code}
> This is caused by 2 separate write operations - 1 for set marker field and 1 
> for actual object. So it's possible that marker is already set to true 
> (causing AlreadySetException on second write attempt) but object is still not 
> set (causing NullPointerException).
> This can be avoided by using single AtomicReference instead to serve both 
> purposes.



--
This message was sent by Atlassian Jira
(v8.3.4#803005)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to