-
Notifications
You must be signed in to change notification settings - Fork 22
feat: Use singleton JsonFactory instance #31 #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
breedx-nr
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @gstoupis for this contribution! This is a nice start.
I left a comment about the race condition in the singleton, but I think it's an easy change.
My instinct would have been to just add a field of JsonFactory to the NewRelicJsonLayout, but this approach (pure singleton) should be fine too.
Thanks!
| private static JsonFactory jsonFactory; | ||
|
|
||
| static JsonFactory getInstance() { | ||
| if (jsonFactory == null) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So it might be a bit pedantic and may not seriously impact real-world applications, but technically there is a race condition here.
Imagine 10 threads, all calling getInstance() at the same time. It is possible for all 10 to pass the null check, then they all create instances and assign them and return them. For some period of time, there will be more than 1 instance of JsonFactory around.
In this case, especially since JsonFactory has no dependencies and is so easy to construct, I think it is easily remedied by changing the static field declaration to:
private final static JsonFactory jsonFactory = new JsonFactory();
and then you can remove the if() in the getter. Should be safer and simpler that way.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch! I'll change it accordingly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in cb71c26
Thanks for the review @breedx-nr! You're right, having it inside the So I thought that creating a new class and having it provide the singleton JsonFactory could be utilized by these other packages well. Of course, if you think it'd be better, I can revert the changes and just add a field of What do you think? |
|
I think that your approach is solid and the ability to reuse in other packages is forward-looking, so let's go with that. |
breedx-nr
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks again!
Re: issue #31