private void removeLibraryIfNeeded() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance();
    ModifiableRootModel model = modelsProvider.getModuleModifiableModel(myModule);
    LibraryOrderEntry goLibraryEntry =
        OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());
    if (goLibraryEntry != null) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                Library library = goLibraryEntry.getLibrary();
                if (library != null) {
                  LibraryTable table = library.getTable();
                  if (table != null) {
                    table.removeLibrary(library);
                    model.removeOrderEntry(goLibraryEntry);
                    modelsProvider.commitModuleModifiableModel(model);
                  }
                } else {
                  modelsProvider.disposeModuleModifiableModel(model);
                }
              });
    } else {
      ApplicationManager.getApplication()
          .runWriteAction(() -> modelsProvider.disposeModuleModifiableModel(model));
    }
  }
  private void attachLibraries(
      @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (!libraryRoots.isEmpty()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                ModuleRootManager model = ModuleRootManager.getInstance(myModule);
                LibraryOrderEntry goLibraryEntry =
                    OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());

                if (goLibraryEntry != null && goLibraryEntry.isValid()) {
                  Library library = goLibraryEntry.getLibrary();
                  if (library != null && !((LibraryEx) library).isDisposed()) {
                    fillLibrary(library, libraryRoots, exclusions);
                  }
                } else {
                  LibraryTable libraryTable =
                      LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject());
                  Library library = libraryTable.createLibrary(getLibraryName());
                  fillLibrary(library, libraryRoots, exclusions);
                  ModuleRootModificationUtil.addDependency(myModule, library);
                }
              });
      showNotification(myModule.getProject());
    } else {
      removeLibraryIfNeeded();
    }
  }