Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ResourcesPlugin: Multithreaded lazy start #1219

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %pluginName
Bundle-SymbolicName: org.eclipse.core.resources; singleton:=true
Bundle-Version: 3.20.100.qualifier
Bundle-Version: 3.20.200.qualifier
Bundle-Activator: org.eclipse.core.resources.ResourcesPlugin
Bundle-Vendor: %providerName
Bundle-Localization: plugin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -888,15 +889,64 @@ protected void restoreMarkers(IResource resource, boolean generateDeltas, IProgr
}
return;
}
IProject[] projects = ((IWorkspaceRoot) resource).getProjects(IContainer.INCLUDE_HIDDEN);
for (IProject project : projects)
if (project.isAccessible())
markerManager.restore(project, generateDeltas, monitor);
forEachProjectInParallel(monitor, project -> {
if (project.isAccessible()) {
markerManager.restore(project, generateDeltas, null);
}
});
if (Policy.DEBUG_RESTORE_MARKERS) {
Policy.debug("Restore Markers for workspace: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
}

@FunctionalInterface
public interface CoreConsumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t) throws CoreException;
}

private void forEachProjectInParallel(IProgressMonitor m, CoreConsumer<IProject> consumer) throws CoreException {
IProject[] projects = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN);
if (projects.length == 0) {
return;
}
SubMonitor subMointor = SubMonitor.convert(m, projects.length);
IStatus[] stats;
// Never use a shared ForkJoinPool.commonPool() as it may be busy with other tasks, which might deadlock.
// Also use a custom ForkJoinWorkerThreadFactory, to prevent issues with a
// potential SecurityManager, since the threads created by it get no permissions.
// See https://github.com/eclipse-platform/eclipse.platform/issues/294
ExecutorService executor = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(),
pool -> new ForkJoinWorkerThread(pool) {
// anonymous subclass to access protected constructor
}, null, false);
try {
stats = executor.submit(() -> Arrays.stream(projects).parallel().map(project -> {
subMointor.split(1);
try {
consumer.accept(project);
} catch (CoreException e) {
return new ResourceStatus(IResourceStatus.FAILED_READ_METADATA, project.getFullPath(),
"Error with project " + project.getName(), e); //$NON-NLS-1$
}
return null;
}).filter(Objects::nonNull).toArray(IStatus[]::new)).get();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You must not call get() here as it blocks, and you don't want to be blocked. Instead you should either return a Stream<..> with an onClose( ... ), a Future<..> or similar or even better a CompletableFuture<..> then you can use that in an event driven non blocking way.

} catch (InterruptedException | ExecutionException e) {
List<Runnable> notExecuted = executor.shutdownNow();
throw new CoreException(Status.error("Error with " + notExecuted.size() + " projects left", e)); //$NON-NLS-1$//$NON-NLS-2$
} finally {
executor.shutdown();
}
if (stats.length > 0) {
laeubi marked this conversation as resolved.
Show resolved Hide resolved
throw new CoreException(new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, stats,
"Error with " + stats.length + " projects", null)); //$NON-NLS-1$ //$NON-NLS-2$
}
}

protected void restoreMasterTable() throws CoreException {
long start = System.currentTimeMillis();
masterTable.clear();
Expand Down Expand Up @@ -926,15 +976,14 @@ protected void restoreMetaInfo(MultiStatus problems, IProgressMonitor monitor) {
if (Policy.DEBUG_RESTORE_METAINFO)
Policy.debug("Restore workspace metainfo: starting..."); //$NON-NLS-1$
long start = System.currentTimeMillis();
IProject[] roots = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN);
for (IProject root : roots) {
//fatal to throw exceptions during startup
try {
try {
forEachProjectInParallel(monitor, root -> {
restoreMetaInfo((Project) root, monitor);
} catch (CoreException e) {
String message = NLS.bind(Messages.resources_readMeta, root.getName());
problems.merge(new ResourceStatus(IResourceStatus.FAILED_READ_METADATA, root.getFullPath(), message, e));
}
});
} catch (CoreException e) {
// fatal to throw exceptions during startup
problems.merge(new ResourceStatus(IResourceStatus.FAILED_READ_METADATA, workspace.getRoot().getFullPath(),
"Could not read metadata", e)); //$NON-NLS-1$
}
if (Policy.DEBUG_RESTORE_METAINFO)
Policy.debug("Restore workspace metainfo: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
Expand Down Expand Up @@ -1778,34 +1827,7 @@ public void visitAndSave(final IResource root) throws CoreException {
// recurse over the projects in the workspace if we were given the workspace root
if (root.getType() == IResource.PROJECT)
return;
IProject[] projects = ((IWorkspaceRoot) root).getProjects(IContainer.INCLUDE_HIDDEN);
// Never use a shared ForkJoinPool.commonPool() as it may be busy with other tasks, which might deadlock.
// Also use a custom ForkJoinWorkerThreadFactory, to prevent issues with a
// potential SecurityManager, since the threads created by it get no permissions.
// See https://github.com/eclipse-platform/eclipse.platform/issues/294
ForkJoinPool forkJoinPool = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(),
pool -> new ForkJoinWorkerThread(pool) {
// anonymous subclass to access protected constructor
}, null, false);
IStatus[] stats;
try {
stats = forkJoinPool.submit(() -> Arrays.stream(projects).parallel().map(project -> {
try {
visitAndSave(project);
} catch (CoreException e) {
return e.getStatus();
}
return null;
}).filter(Objects::nonNull).toArray(IStatus[]::new)).get();
} catch (InterruptedException | ExecutionException e) {
throw new CoreException(Status.error(Messages.resources_saveProblem, e));
} finally {
forkJoinPool.shutdown();
}
if (stats.length > 0) {
throw new CoreException(new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, stats,
Messages.resources_saveProblem, null));
}
forEachProjectInParallel(null, this::visitAndSave);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,21 @@
import org.eclipse.core.internal.resources.Workspace;
import org.eclipse.core.internal.utils.Messages;
import org.eclipse.core.internal.utils.Policy;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.service.datalocation.Location;
import org.eclipse.osgi.service.debug.DebugOptions;
import org.eclipse.osgi.service.debug.DebugOptionsListener;
import org.osgi.framework.*;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

Expand Down Expand Up @@ -419,7 +427,7 @@ public final class ResourcesPlugin extends Plugin {
* @see #getSystemEncoding()
*/
public static String getEncoding() {
ResourcesPlugin resourcesPlugin = plugin;
ResourcesPlugin resourcesPlugin = getPlugin();
if (resourcesPlugin == null) {
return getSystemEncoding();
}
Expand Down Expand Up @@ -475,7 +483,21 @@ private static String getSystemEncoding() {
* @return the single instance of this plug-in runtime class
*/
public static ResourcesPlugin getPlugin() {
return plugin;
if (plugin == null) {
return null;
}
return plugin.initialized();
}

private ResourcesPlugin initialized() {
ServiceTracker<Location, Workspace> t = instanceLocationTracker;
if (t != null && t.size() == 0) {
synchronized (t) {
// lazy initialize
t.open();
}
}
return this;
}

/**
Expand All @@ -491,10 +513,8 @@ public static ResourcesPlugin getPlugin() {
* class.
*/
public static IWorkspace getWorkspace() {
ResourcesPlugin resourcesPlugin = plugin;
ResourcesPlugin resourcesPlugin = getPlugin();
if (resourcesPlugin == null) {
// this happens when the resource plugin is shut down already... or never
// started!
throw new IllegalStateException(Messages.resources_workspaceClosedStatic);
}
Workspace workspace = resourcesPlugin.workspaceInitCustomizer.workspace;
Expand All @@ -520,6 +540,7 @@ public void stop(BundleContext context) throws Exception {
// save the preferences for this plug-in
getPlugin().savePluginPreferences();
plugin = null;
instanceLocationTracker = null;
}

/**
Expand All @@ -542,7 +563,7 @@ public void start(BundleContext context) throws Exception {
workspaceInitCustomizer);
plugin = this; // must before open the tracker, as this can cause the registration of the
// workspace and this might trigger code that calls the static method then.
instanceLocationTracker.open();
new Thread(this::initialized, "Async ResourcesPlugin start").start(); //$NON-NLS-1$
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still wrong, the contract of the Resources plugin is that it tracks the workspace in the activator, as the activation usually (but that's not guaranteed!) happens by a lazy-activation and in this case must be guarded by the classloader lock.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with Cristoph. The code expected to have workspace initialized after activator is done, not asynchronously after that.

Please put breakpoint at org.eclipse.core.internal.resources.Workspace.open(IProgressMonitor) and check that this is executed in context of org.eclipse.core.resources.ResourcesPlugin.start(BundleContext) call.

Initialization of ResourcesPlugin should be changed very carefully, there are different actors playing here and not everything can be validated via automated tests.

}

private final class WorkspaceInitCustomizer implements ServiceTrackerCustomizer<Location, Workspace> {
Expand Down
2 changes: 1 addition & 1 deletion ua/org.eclipse.help.base/META-INF/MANIFEST.MF
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %help_base_plugin_name
Bundle-SymbolicName: org.eclipse.help.base; singleton:=true
Bundle-Version: 4.4.300.qualifier
Bundle-Version: 4.4.400.qualifier
Bundle-Activator: org.eclipse.help.internal.base.HelpBasePlugin
Bundle-Vendor: %providerName
Bundle-Localization: plugin
Expand Down
2 changes: 1 addition & 1 deletion ua/org.eclipse.help.base/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</parent>
<groupId>org.eclipse.help</groupId>
<artifactId>org.eclipse.help.base</artifactId>
<version>4.4.300-SNAPSHOT</version>
<version>4.4.400-SNAPSHOT</version>
<packaging>eclipse-plugin</packaging>
<properties>
<defaultSigning-excludeInnerJars>true</defaultSigning-excludeInnerJars>
Expand Down
Loading