From 65edd6a16e5c4e683569b70083263c4c45200a9b Mon Sep 17 00:00:00 2001 From: Alexander Udalov Date: Wed, 12 Mar 2014 22:14:03 +0400 Subject: [PATCH] Make KotlinBinaryClassCache thread-local --- .../kotlin/KotlinBinaryClassCache.java | 38 +++++++++++++------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/kotlin/KotlinBinaryClassCache.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/kotlin/KotlinBinaryClassCache.java index 85410d24291..7af5a65681d 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/kotlin/KotlinBinaryClassCache.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/kotlin/KotlinBinaryClassCache.java @@ -16,6 +16,7 @@ package org.jetbrains.jet.lang.resolve.kotlin; +import com.intellij.openapi.Disposable; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; @@ -23,23 +24,36 @@ import com.intellij.util.containers.SLRUCache; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public final class KotlinBinaryClassCache { +public final class KotlinBinaryClassCache implements Disposable { // This cache must be small: we only query the same file a few times in a row (from different places) - // Since it is on application level we should be careful about this cache. Consider profiling multiple projects indexing simultaneously. - private final SLRUCache> cache = new SLRUCache>(2, 2) { - @NotNull - @Override - public Ref createValue(VirtualFile virtualFile) { - return Ref.create(VirtualFileKotlinClass.create(virtualFile)); - } - }; + // It's local to each thread: we don't want a single instance to synchronize access on, because VirtualFileKotlinClass.create involves + // reading files from disk and may take some time + private final ThreadLocal>> cache = + new ThreadLocal>>() { + @Override + protected SLRUCache> initialValue() { + return new SLRUCache>(2, 2) { + @NotNull + @Override + public Ref createValue(VirtualFile virtualFile) { + return Ref.create(VirtualFileKotlinClass.create(virtualFile)); + } + }; + } + }; @Nullable public static KotlinJvmBinaryClass getKotlinBinaryClass(@NotNull VirtualFile file) { KotlinBinaryClassCache service = ServiceManager.getService(KotlinBinaryClassCache.class); - synchronized (service.cache) { - return service.cache.get(file).get(); - } + return service.cache.get().get(file).get(); + } + + @Override + public void dispose() { + // This is only relevant for tests. We create a new instance of Application for each test, and so a new instance of this service is + // also created for each test. However all tests share the same event dispatch thread, which would collect all instances of this + // thread-local if they're not removed properly. Each instance would transitively retain VFS resulting in OutOfMemoryError + cache.remove(); } }