Charset.lookupViaProviders uses new ServiceLoader instance on each miss.

Bernd Eckenfels ecki at
Mon Jan 12 19:09:48 UTC 2015


I see some strange scalability problem in an application which uses a
few exernal Charsets which are provided by ServiceLoader. When I check
the code for Charset.forName()/lookup() I can the 2-entry LRU cache for
charsets, and if those caches do not find the charset, it will check
standard, extended and loaded charsets.

The later function is here:

And it uses ServiceLoader.load() on each lookup.

This is unfortunate as it creates a new ServideLoader instance which in
turn has its own (empty) service provider cache. So every time a
extended charset is loaded (or an unknown charset is requested) it has
to parse all the manifests. But what it is even worse, it also has to
actually instantiate the found provider (again), so in some cases that
provider can also not cache.

Do I read the code correct?

I think a quick fix would be to hold onto the ServiceLoader. Since it
is initialized with the System classloader, there is no need to have a
new one on each load. It migh also be worth considerung another 2-level
LRU cache inside lookupViaProviders. I am not sure if a reload would be
needed for that kind of system serviceloader?

Here is a Java7 stacktrace, I think it has'nt changed much in Java9:

java.lang.Thread.State: RUNNABLE
  at sun.misc.ASCIICaseInsensitiveComparator.isUpper(
  at sun.misc.ASCIICaseInsensitiveComparator.toLower(
  at java.util.TreeMap.put(
  at sun.nio.cs.AbstractCharsetProvider.put(
  at sun.nio.cs.AbstractCharsetProvider.charset(
  - locked <0x00002b0df808c1e0> (a sun.nio.cs.ext.ExtendedCharsets)
  at sun.nio.cs.ext.ExtendedCharsets.<init>(
  at sun.reflect.GeneratedConstructorAccessor398.newInstance(Unknown Source)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
  at java.lang.reflect.Constructor.newInstance(
>>at java.lang.Class.newInstance(
  at java.util.ServiceLoader$
  at java.util.ServiceLoader$
  at java.nio.charset.Charset$1.getNext(
  at java.nio.charset.Charset$1.hasNext(
  at java.nio.charset.Charset$
  at java.nio.charset.Charset$
  at Method)
>>at java.nio.charset.Charset.lookupViaProviders(
  at java.nio.charset.Charset.lookup2(
  at java.nio.charset.Charset.lookup(
  at java.nio.charset.Charset.isSupported(
  at sun.nio.cs.StreamDecoder.forInputStreamReader(

In the specific case it also looks like no thread local decoder was used, but I havent looked into that, yet.


More information about the core-libs-dev mailing list