Closed danomatic closed 6 years ago
Can you point to any evidence that String.intern() can be used for locking?
There are lots of contradicting posts on the subject. Here for example is stated that it's a bad practice: https://stackoverflow.com/questions/133988/problem-with-synchronizing-on-string-objects
Other suggest using a mutex, but wether this is worth it is debatable.
My rough understanding is that it is safe and efficient, especially for Java 7 and 8. Some details here: http://java-performance.info/string-intern-in-java-6-7-8/
But don't take my word for it. Synchronizing all cache access across all threads was bad for our application, especially because we have slow API calls inside the @Cacheable method.
I've been investigating a little and apart from the article you reference, I haven't found any other evidence that suggests we can safely lock on String.intern. Also the article is not explicitly stating we can lock on it.
I've found another solution though that I think can suit our need. It has been suggested (here https://stackoverflow.com/questions/11124539/how-to-acquire-a-lock-by-a-key) to use the Striped class from Guava. The javadoc on the class explains it all: https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/Striped.java
If you rewrite the code to use the Striped class, I will accept the PR.
seems too bad to pull in all of guava for that, but it does look nice.
What about this lighter solution from the same SO post? It seems very similar. https://stackoverflow.com/a/36054928/2020766
Yes, it is based on the same idea. We can go for it as I also prefer keeping the library light.
We should decide on a default value for the size. And make it configurable.
Lock using the cache key instead of a global lock, which allows more concurrency without race conditions.