Java Code Examples for com.intellij.util.ConcurrencyUtil#cacheOrGet()

The following examples show how to use com.intellij.util.ConcurrencyUtil#cacheOrGet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiplePsiFilesPerDocumentFileViewProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected PsiFile getPsiInner(@Nonnull final Language target) {
  PsiFileImpl file = myRoots.get(target);
  if (file == null) {
    if (!shouldCreatePsi()) return null;
    if (target != getBaseLanguage() && !getLanguages().contains(target)) {
      return null;
    }
    file = createPsiFileImpl(target);
    if (file == null) return null;
    if (myOriginal != null) {
      final PsiFile originalFile = myOriginal.getPsi(target);
      if (originalFile != null) {
        file.setOriginalFile(originalFile);
      }
    }
    file = ConcurrencyUtil.cacheOrGet(myRoots, target, file);
  }
  return file;
}
 
Example 2
Source File: ClassMetadataProxy.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
private ClassMetadata getTarget(Module module) {
  String fqn = typeToFqn(module, type);
  if (fqn != null) {
    String userDataKeyRef = "spring_assistant_plugin_class_metadata:" + fqn;
    Key<CachedValue<ClassMetadata>> classMetadataKey =
        ConcurrencyUtil.cacheOrGet(fqnToKey, userDataKeyRef, Key.create(userDataKeyRef));
    return getCachedValue(targetClass, classMetadataKey, () -> {
      log.debug("Creating metadata instance for " + userDataKeyRef);
      Set<PsiClass> dependencies = computeDependencies(module, type);
      if (dependencies != null) {
        return create(newClassMetadata(type), dependencies);
      }
      return null;
    });
  }
  return null;
}
 
Example 3
Source File: ConcurrentMultiMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void putValue(@Nonnull K key, V value) {
  Collection<V> collection = myMap.get(key);
  if (collection == null) {
    Collection<V> newCollection = createCollection();
    collection = ConcurrencyUtil.cacheOrGet((ConcurrentMap<K, Collection<V>>)myMap, key, newCollection);
  }
  collection.add(value);
}
 
Example 4
Source File: NamedObjectProviderBinding.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void registerProvider(@NonNls @Nonnull String[] names, @Nonnull ElementPattern filter, boolean caseSensitive, @Nonnull Provider provider, final double priority) {
  final ConcurrentMap<String, List<ProviderInfo<Provider, ElementPattern>>> map = caseSensitive ? myNamesToProvidersMap : myNamesToProvidersMapInsensitive;

  for (final String attributeName : names) {
    List<ProviderInfo<Provider, ElementPattern>> psiReferenceProviders = map.get(attributeName);

    if (psiReferenceProviders == null) {
      String key = caseSensitive ? attributeName : attributeName.toLowerCase();
      psiReferenceProviders = ConcurrencyUtil.cacheOrGet(map, key, ContainerUtil.<ProviderInfo<Provider, ElementPattern>>createLockFreeCopyOnWriteList());
    }

    psiReferenceProviders.add(new ProviderInfo<Provider, ElementPattern>(provider, filter, priority));
  }
}
 
Example 5
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void appendResult(@Nonnull PsiFile file, @Nonnull InspectionResult result) {
  List<InspectionResult> resultList = this.result.get(file);
  if (resultList == null) {
    resultList = ConcurrencyUtil.cacheOrGet(this.result, file, new ArrayList<>());
  }
  synchronized (resultList) {
    resultList.add(result);
  }
}
 
Example 6
Source File: MessageBusImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
void notifyOnSubscription(@Nonnull MessageBusConnectionImpl connection, @Nonnull Topic<?> topic) {
  checkNotDisposed();
  List<MessageBusConnectionImpl> topicSubscribers = mySubscribers.get(topic);
  if (topicSubscribers == null) {
    topicSubscribers = ContainerUtil.createLockFreeCopyOnWriteList();
    topicSubscribers = ConcurrencyUtil.cacheOrGet(mySubscribers, topic, topicSubscribers);
  }

  topicSubscribers.add(connection);

  myRootBus.clearSubscriberCache();
}
 
Example 7
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private ConcurrentMap<VirtualFile, PsiDirectory> getVFileToPsiDirMap() {
  ConcurrentMap<VirtualFile, PsiDirectory> map = myVFileToPsiDirMap.get();
  if (map == null) {
    map = ConcurrencyUtil.cacheOrGet(myVFileToPsiDirMap, ContainerUtil.createConcurrentSoftValueMap());
  }
  return map;
}
 
Example 8
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Nonnull
public ConcurrentMap<VirtualFile, FileViewProvider> getVFileToViewProviderMap() {
  ConcurrentMap<VirtualFile, FileViewProvider> map = myVFileToViewProviderMap.get();
  if (map == null) {
    map = ConcurrencyUtil.cacheOrGet(myVFileToViewProviderMap, ContainerUtil.createConcurrentWeakValueMap());
  }
  return map;
}
 
Example 9
Source File: SemServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private SemCacheChunk getOrCreateChunk(final PsiElement element) {
  SemCacheChunk chunk = obtainChunk(element);
  if (chunk == null) {
    chunk = ConcurrencyUtil.cacheOrGet(myCache, element, new SemCacheChunk());
  }
  return chunk;
}
 
Example 10
Source File: VirtualFilePointerManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void registerDisposable(@Nonnull Disposable parentDisposable, @Nonnull VirtualFilePointerImpl pointer) {
  DelegatingDisposable result = ourInstances.get(parentDisposable);
  if (result == null) {
    DelegatingDisposable newDisposable = new DelegatingDisposable(parentDisposable, pointer);
    result = ConcurrencyUtil.cacheOrGet(ourInstances, parentDisposable, newDisposable);
    if (result == newDisposable) {
      Disposer.register(parentDisposable, result);
      return;
    }
  }
  result.increment(pointer);
}
 
Example 11
Source File: LibraryScopeCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public GlobalSearchScope getScopeForSdk(@Nonnull final ModuleExtensionWithSdkOrderEntry sdkOrderEntry) {
  final String jdkName = sdkOrderEntry.getSdkName();
  if (jdkName == null) return GlobalSearchScope.allScope(myProject);
  GlobalSearchScope scope = mySdkScopes.get(jdkName);
  if (scope == null) {
    scope = new SdkScope(myProject, sdkOrderEntry);
    return ConcurrencyUtil.cacheOrGet(mySdkScopes, jdkName, scope);
  }
  return scope;
}
 
Example 12
Source File: LibraryScopeCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public GlobalSearchScope getScopeForLibraryUsedIn(@Nonnull List<Module> modulesLibraryIsUsedIn) {
  GlobalSearchScope scope = myLibraryScopes.get(modulesLibraryIsUsedIn);
  if (scope != null) {
    return scope;
  }
  GlobalSearchScope newScope = modulesLibraryIsUsedIn.isEmpty()
                               ? myLibrariesOnlyScope
                               : new LibraryRuntimeClasspathScope(myProject, modulesLibraryIsUsedIn);
  return ConcurrencyUtil.cacheOrGet(myLibraryScopes, modulesLibraryIsUsedIn, newScope);
}
 
Example 13
Source File: AttributesFlyweight.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static AttributesFlyweight create(Color foreground,
                                         Color background,
                                         @JdkConstants.FontStyle int fontType,
                                         Color effectColor,
                                         EffectType effectType,
                                         @Nonnull Map<EffectType, Color> additionalEffects,
                                         Color errorStripeColor) {
  FlyweightKey key = ourKey.get();
  if (key == null) {
    ourKey.set(key = new FlyweightKey());
  }
  key.foreground = foreground;
  key.background = background;
  key.fontType = fontType;
  key.effectColor = effectColor;
  key.effectType = effectType;
  key.myAdditionalEffects = additionalEffects.isEmpty() ? Collections.emptyMap() : new HashMap<>(additionalEffects);
  key.errorStripeColor = errorStripeColor;

  AttributesFlyweight flyweight = entries.get(key);
  if (flyweight != null) {
    return flyweight;
  }

  return ConcurrencyUtil.cacheOrGet(entries, key.clone(), new AttributesFlyweight(key));
}
 
Example 14
Source File: HighlightingSessionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
static HighlightingSession getOrCreateHighlightingSession(@Nonnull PsiFile psiFile, @Nonnull DaemonProgressIndicator progressIndicator, @Nullable EditorColorsScheme editorColorsScheme) {
  HighlightingSession session = getHighlightingSession(psiFile, progressIndicator);
  if (session == null) {
    ConcurrentMap<PsiFile, HighlightingSession> map = progressIndicator.getUserData(HIGHLIGHTING_SESSION);
    if (map == null) {
      map = progressIndicator.putUserDataIfAbsent(HIGHLIGHTING_SESSION, ContainerUtil.newConcurrentMap());
    }
    session = ConcurrencyUtil.cacheOrGet(map, psiFile, new HighlightingSessionImpl(psiFile, progressIndicator, editorColorsScheme));
  }
  return session;
}
 
Example 15
Source File: AWTIconLoaderFacade.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public SwingImageRef findIcon(URL url, boolean useCache) {
  if (url == null) {
    return null;
  }
  CachedImageIcon icon = myIconsCache.get(url);
  if (icon == null) {
    icon = new CachedImageIcon(url);
    if (useCache) {
      icon = ConcurrencyUtil.cacheOrGet(myIconsCache, url, icon);
    }
  }
  return icon;
}
 
Example 16
Source File: RefManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public RefModule getRefModule(@Nullable Module module) {
  if (module == null) {
    return null;
  }
  RefModule refModule = myModules.get(module);
  if (refModule == null) {
    refModule = ConcurrencyUtil.cacheOrGet(myModules, module, new RefModuleImpl(module, this));
  }
  return refModule;
}
 
Example 17
Source File: LowLevelSearchUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int[] getTextOccurrences(@Nonnull CharSequence text,
                                        int startOffset,
                                        int endOffset,
                                        @Nonnull StringSearcher searcher,
                                        @Nullable ProgressIndicator progress) {
  if (endOffset > text.length()) {
    throw new IllegalArgumentException("end: " + endOffset + " > length: " + text.length());
  }
  Map<StringSearcher, int[]> cachedMap = cache.get(text);
  int[] cachedOccurrences = cachedMap == null ? null : cachedMap.get(searcher);
  boolean hasCachedOccurrences = cachedOccurrences != null && cachedOccurrences[0] <= startOffset && cachedOccurrences[1] >= endOffset;
  if (!hasCachedOccurrences) {
    TIntArrayList occurrences = new TIntArrayList();
    int newStart = Math.min(startOffset, cachedOccurrences == null ? startOffset : cachedOccurrences[0]);
    int newEnd = Math.max(endOffset, cachedOccurrences == null ? endOffset : cachedOccurrences[1]);
    occurrences.add(newStart);
    occurrences.add(newEnd);
    for (int index = newStart; index < newEnd; index++) {
      if (progress != null) progress.checkCanceled();
      //noinspection AssignmentToForLoopParameter
      index = searcher.scan(text, index, newEnd);
      if (index < 0) break;
      if (checkJavaIdentifier(text, 0, text.length(), searcher, index)) {
        occurrences.add(index);
      }
    }
    cachedOccurrences = occurrences.toNativeArray();
    if (cachedMap == null) {
      cachedMap = ConcurrencyUtil.cacheOrGet(cache, text, Maps.newConcurrentSoftHashMap());
    }
    cachedMap.put(searcher, cachedOccurrences);
  }
  TIntArrayList offsets = new TIntArrayList(cachedOccurrences.length - 2);
  for (int i = 2; i < cachedOccurrences.length; i++) {
    int occurrence = cachedOccurrences[i];
    if (occurrence > endOffset - searcher.getPatternLength()) break;
    if (occurrence >= startOffset) {
      offsets.add(occurrence);
    }
  }
  return offsets.toNativeArray();
}
 
Example 18
Source File: WeakInterner.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public T intern(@Nonnull T name) {
  return ConcurrencyUtil.cacheOrGet(myMap, name, name);
}
 
Example 19
Source File: TextAttributesKey.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static TextAttributesKey find(@Nonnull @NonNls String externalName) {
  return ConcurrencyUtil.cacheOrGet(ourRegistry, externalName, new TextAttributesKey(externalName));
}
 
Example 20
Source File: UniqueVFilePathBuilderImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static String getUniqueVirtualFilePath(final Project project, VirtualFile file, final boolean skipNonOpenedFiles, GlobalSearchScope scope) {
  Key<CachedValue<Map<GlobalSearchScope, Map<String, UniqueNameBuilder<VirtualFile>>>>> key =
          skipNonOpenedFiles ?  ourShortNameOpenedBuilderCacheKey:ourShortNameBuilderCacheKey;
  CachedValue<Map<GlobalSearchScope, Map<String, UniqueNameBuilder<VirtualFile>>>> data = project.getUserData(key);
  if (data == null) {
    project.putUserData(key, data = CachedValuesManager.getManager(project).createCachedValue(
            () -> new CachedValueProvider.Result<Map<GlobalSearchScope, Map<String, UniqueNameBuilder<VirtualFile>>>>(
                    new ConcurrentHashMap<>(2),
                    PsiModificationTracker.MODIFICATION_COUNT,
                    //ProjectRootModificationTracker.getInstance(project),
                    //VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS,
                    FileEditorManagerImpl.OPEN_FILE_SET_MODIFICATION_COUNT
            ), false));
  }

  ConcurrentMap<GlobalSearchScope, Map<String, UniqueNameBuilder<VirtualFile>>> scope2ValueMap =
          (ConcurrentMap<GlobalSearchScope, Map<String,UniqueNameBuilder<VirtualFile>>>)data.getValue();
  Map<String, UniqueNameBuilder<VirtualFile>> valueMap = scope2ValueMap.get(scope);
  if (valueMap == null) {
    valueMap = ConcurrencyUtil.cacheOrGet(scope2ValueMap, scope, ContainerUtil.createConcurrentSoftValueMap());
  }

  final String fileName = file.getName();
  UniqueNameBuilder<VirtualFile> uniqueNameBuilderForShortName = valueMap.get(fileName);

  if (uniqueNameBuilderForShortName == null) {
    final UniqueNameBuilder<VirtualFile> builder = filesWithTheSameName(
            fileName,
            project,
            skipNonOpenedFiles,
            scope
    );
    valueMap.put(fileName, builder != null ? builder:ourEmptyBuilder);
    uniqueNameBuilderForShortName = builder;
  } else if (uniqueNameBuilderForShortName == ourEmptyBuilder) {
    uniqueNameBuilderForShortName = null;
  }

  if (uniqueNameBuilderForShortName != null && uniqueNameBuilderForShortName.contains(file)) {
    if (file instanceof VirtualFilePathWrapper) {
      return ((VirtualFilePathWrapper)file).getPresentablePath();
    }
    return uniqueNameBuilderForShortName.getShortPath(file);
  }
  return file.getName();
}