Replace synchronized
with j.u.c.l.ReentrantLock
for Loom
#3480
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Goal
In Sep 2023, JDK 21 will be released. One of the most anticipated feature - Project Loom aka Virtual threads.
One of the problems with the current implementation, are
synchronized
blocks:From here: https://softwaremill.com/what-is-blocking-in-loom/#synchronization-problems
The main goal of this PR is to replace
synchronized
blocks withReentrantLock
s who are not susceptible to this problem.Approach
My approach was quite simple: replace
synchronized
blocks withReentrantLock
's. However, in a few cases, though, I believe we can get rid of synchronization at all:I replaced it with:
The field
jsonObjectMapper
marked asvolatile
, thus we establish connection (acquire-release) between thread which writes to this field and other threads which will read this field.However, there is still a scenario when multiple threads will enter this method at the same time and see
null
: all of them will create an object and write it to a variable. This won't cause any problems since theDefaultGsonObjectMapper
is stateless, but the object creation operation itself may be more costly than lock acquisition. Do you think it is worthwhile to return the lock here?Since
builders
isConcurrentHashMap
, we can avoid synchronization and either useputIfAbsent
or, if creation ofResultSetBuilder
andGraphCacheImpl
is expensive, usecomputeIfAbsent
:Alternative
It worth mentioning a comment on Reddit left by Ron Pressler (Project Loom lead) that the work on making
synchronized
not pin is underway.Leave
synchronized
blocks as is and wait for next version of JDK (22+).