com.intellij.util.ConcurrencyUtil Java Examples

The following examples show how to use com.intellij.util.ConcurrencyUtil. 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: 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 #2
Source File: PsiReferenceRegistrarImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void registerNamedReferenceProvider(@Nonnull String[] names,
                                            final PsiNamePatternCondition<?> nameCondition,
                                            @Nonnull Class scopeClass,
                                            final boolean caseSensitive,
                                            @Nonnull PsiReferenceProvider provider,
                                            final double priority,
                                            @Nonnull ElementPattern pattern) {
  NamedObjectProviderBinding<PsiReferenceProvider> providerBinding = myNamedBindingsMap.get(scopeClass);

  if (providerBinding == null) {
    providerBinding = ConcurrencyUtil.cacheOrGet(myNamedBindingsMap, scopeClass, new NamedObjectProviderBinding<PsiReferenceProvider>() {
      @Override
      protected String getName(final PsiElement position) {
        return nameCondition.getPropertyValue(position);
      }
    });
  }

  providerBinding.registerProvider(names, pattern, caseSensitive, provider, priority);
}
 
Example #3
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 #4
Source File: ConcurrentFactoryMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public V get(Object key) {
  ConcurrentMap<K, V> map = myMap;
  K k = notNull(key);
  V value = map.get(k);
  if (value == null) {
    RecursionGuard.StackStamp stamp = RecursionManager.markStack();
    //noinspection unchecked
    value = create((K)key);
    if (stamp.mayCacheNow()) {
      V v = notNull(value);
      value = ConcurrencyUtil.cacheOrGet(map, k, v);
    }
  }
  return nullize(value);
}
 
Example #5
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 #6
Source File: MultiThreadSearcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Runnable createFinisherTask(CountDownLatch latch, FullSearchResultsAccumulator accumulator, ProgressIndicator indicator) {
  return ConcurrencyUtil.underThreadNameRunnable("SE-FinisherTask", () -> {
    try {
      latch.await();
      if (!indicator.isCanceled()) {
        accumulator.searchFinished();
      }
      indicator.stop();
    }
    catch (InterruptedException e) {
      LOG.debug("Finisher interrupted before search process is finished");
    }
  });
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: BaseDataReader.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void start(@Nonnull String presentableName) {
  if (StringUtil.isEmptyOrSpaces(presentableName)) {
    LOG.warn(new Throwable("Must provide not-empty presentable name"));
  }
  if (myFinishedFuture == null) {
    myFinishedFuture = executeOnPooledThread(() -> {
      if (StringUtil.isEmptyOrSpaces(presentableName)) {
        doRun();
      }
      else {
        ConcurrencyUtil.runUnderThreadName("BaseDataReader: " + presentableName, this::doRun);
      }
    });
  }
}
 
Example #14
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 #15
Source File: LowMemoryWatcherManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
public LowMemoryWatcherManager(@Nonnull ExecutorService backendExecutorService) {
  // whether LowMemoryWatcher runnables should be executed on the same thread that the low memory events come
  myExecutorService = SystemProperties.getBooleanProperty("low.memory.watcher.sync", false)
                      ? ConcurrencyUtil.newSameThreadExecutorService()
                      : SequentialTaskExecutor.createSequentialApplicationPoolExecutor("LowMemoryWatcherManager", backendExecutorService);

  myMemoryPoolMXBeansFuture = initializeMXBeanListenersLater(backendExecutorService);
}
 
Example #16
Source File: FastBuildChangedFilesService.java    From intellij with Apache License 2.0 5 votes vote down vote up
FastBuildChangedFilesService(Project project) {
  this(
      project,
      BlazeProjectDataManager.getInstance(project),
      listeningDecorator(
          ConcurrencyUtil.newSingleThreadExecutor(
              FastBuildChangedFilesService.class.getSimpleName() + "-" + project.getName())));
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: CacheUpdateRunner.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Runnable createRunnable(@Nonnull Project project,
                                       @Nonnull FileContentQueue queue,
                                       @Nonnull ProgressUpdater progressUpdater,
                                       @Nonnull ProgressIndicator suspendableIndicator,
                                       @Nonnull ProgressIndicatorBase innerIndicator,
                                       @Nonnull AtomicBoolean isFinished,
                                       @Nonnull Consumer<? super FileContent> fileProcessor) {
  return ConcurrencyUtil.underThreadNameRunnable("Indexing", new MyRunnable(innerIndicator, suspendableIndicator, queue, isFinished, progressUpdater, project, fileProcessor));
}
 
Example #23
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 #24
Source File: BoundedTaskExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void wrapAndExecute(@Nonnull Runnable firstTask, long status) {
  try {
    AtomicReference<Runnable> currentTask = new AtomicReference<>(firstTask);
    myBackendExecutor.execute(new Runnable() {
      @Override
      public void run() {
        if (myChangeThreadName) {
          String name = myName;
          if (Boolean.TRUE/*StartUpMeasurer.isEnabled()*/) {
            name += "[" + Thread.currentThread().getName() + "]";
          }
          ConcurrencyUtil.runUnderThreadName(name, this::execute);
        }
        else {
          execute();
        }
      }

      private void execute() {
        Runnable task = currentTask.get();
        do {
          currentTask.set(task);
          doRun(task);
          task = pollOrGiveUp(status);
        }
        while (task != null);
      }

      @Override
      public String toString() {
        return String.valueOf(info(currentTask.get()));
      }
    });
  }
  catch (Error | RuntimeException e) {
    myStatus.decrementAndGet();
    throw e;
  }
}
 
Example #25
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 #26
Source File: RefCountingStorage.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
protected ExecutorService createExecutor() {
  return new ThreadPoolExecutor(1, 1, Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), ConcurrencyUtil
          .newNamedThreadFactory("RefCountingStorage write content helper"));
}
 
Example #27
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 #28
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();
}
 
Example #29
Source File: FileWatcher.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static ExecutorService executor() {
  boolean async = Registry.is("vfs.filewatcher.works.in.async.way");
  return async ? AppExecutorUtil.createBoundedApplicationPoolExecutor("File Watcher", 1) : ConcurrencyUtil.newSameThreadExecutorService();
}
 
Example #30
Source File: FileStatusMap.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int getThreadNum() {
  return ConcurrencyUtil.cacheOrGet(threads, Thread.currentThread(), threads.size());
}