1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Bug 540373: Format some Java files that were missed

Some files which has other cleanups applied meant they needed to be
reformatted again. e.g. the removing of type parameters shortened
some lines of code that meant the wrapping changed.

Change-Id: I68ca09567b9530cc2a085c33923642b6de2ec77b
This commit is contained in:
Jonah Graham 2018-11-23 13:04:51 +00:00
parent ff75ae80fa
commit 3caea240a3
80 changed files with 2326 additions and 2518 deletions

View file

@ -76,7 +76,7 @@ public class AutoconfSubstRule implements IPredicateRule {
// A valid id has some alphabetic character in it. // A valid id has some alphabetic character in it.
isId = true; isId = true;
} else if (c >= '0' && c <= '9' || c == '_') { } else if (c >= '0' && c <= '9' || c == '_') {
// continue // continue
} else if (c == '@' && isId) } else if (c == '@' && isId)
return getSuccessToken(); return getSuccessToken();
else else

View file

@ -45,8 +45,7 @@ public final class PathInfo {
fQuoteIncludePaths = quoteIncludePaths != null && quoteIncludePaths.length != 0 fQuoteIncludePaths = quoteIncludePaths != null && quoteIncludePaths.length != 0
? (IPath[]) quoteIncludePaths.clone() ? (IPath[]) quoteIncludePaths.clone()
: EMPTY_PATH_ARRAY; : EMPTY_PATH_ARRAY;
fSymbols = symbols != null && symbols.size() != 0 ? getInternedHashMap(symbols) fSymbols = symbols != null && symbols.size() != 0 ? getInternedHashMap(symbols) : new HashMap<>(0);
: new HashMap<>(0);
fIncludeFiles = includeFiles != null && includeFiles.length != 0 ? (IPath[]) includeFiles.clone() fIncludeFiles = includeFiles != null && includeFiles.length != 0 ? (IPath[]) includeFiles.clone()
: EMPTY_PATH_ARRAY; : EMPTY_PATH_ARRAY;
fMacroFiles = macroFiles != null && macroFiles.length != 0 ? (IPath[]) macroFiles.clone() : EMPTY_PATH_ARRAY; fMacroFiles = macroFiles != null && macroFiles.length != 0 ? (IPath[]) macroFiles.clone() : EMPTY_PATH_ARRAY;

View file

@ -339,8 +339,7 @@ public class DiscoveredPathManager implements IDiscoveredPathManager, IResourceC
PerFileDiscoveredPathContainer container = new PerFileDiscoveredPathContainer(project); PerFileDiscoveredPathContainer container = new PerFileDiscoveredPathContainer(project);
CoreModel.setPathEntryContainer(new ICProject[] { cProject }, container, null); CoreModel.setPathEntryContainer(new ICProject[] { cProject }, container, null);
if (changedResources != null) { if (changedResources != null) {
List<PathEntryContainerChanged> changeDelta = new ArrayList<>( List<PathEntryContainerChanged> changeDelta = new ArrayList<>(changedResources.size());
changedResources.size());
for (IResource resource : changedResources) { for (IResource resource : changedResources) {
IPath path = resource.getFullPath(); IPath path = resource.getFullPath();
changeDelta.add( changeDelta.add(

View file

@ -338,8 +338,7 @@ public class PerProjectSICollector implements IScannerInfoCollector3, IScannerIn
LinkedHashMap<String, SymbolEntry> persistedSymbols = discPathInfo.getSymbolMap(); LinkedHashMap<String, SymbolEntry> persistedSymbols = discPathInfo.getSymbolMap();
// Step 3. Merge scanner config from steps 1 and 2 // Step 3. Merge scanner config from steps 1 and 2
LinkedHashMap<String, SymbolEntry> candidateSymbols = new LinkedHashMap<>( LinkedHashMap<String, SymbolEntry> candidateSymbols = new LinkedHashMap<>(persistedSymbols);
persistedSymbols);
addedSymbols |= ScannerConfigUtil.scAddSymbolEntryMap2SymbolEntryMap(candidateSymbols, addedSymbols |= ScannerConfigUtil.scAddSymbolEntryMap2SymbolEntryMap(candidateSymbols,
sumDiscoveredSymbols); sumDiscoveredSymbols);

View file

@ -58,8 +58,7 @@ public class Preconditions extends TestCase {
IContentType contentTypeC = manager.getContentType(CCorePlugin.CONTENT_TYPE_CSOURCE); IContentType contentTypeC = manager.getContentType(CCorePlugin.CONTENT_TYPE_CSOURCE);
fileExts.addAll(Arrays.asList(contentTypeC.getFileSpecs(IContentType.FILE_EXTENSION_SPEC))); fileExts.addAll(Arrays.asList(contentTypeC.getFileSpecs(IContentType.FILE_EXTENSION_SPEC)));
Set<String> expectedExts = new TreeSet<>( Set<String> expectedExts = new TreeSet<>(Arrays.asList(new String[] { "C", "c", "c++", "cc", "cpp", "cxx" }));
Arrays.asList(new String[] { "C", "c", "c++", "cc", "cpp", "cxx" }));
assertEquals("Precodition FAILED - Content Types do not match expected defaults.", expectedExts.toString(), assertEquals("Precodition FAILED - Content Types do not match expected defaults.", expectedExts.toString(),
fileExts.toString()); fileExts.toString());
} }

View file

@ -2163,8 +2163,7 @@ public class ManagedBuildManager extends AbstractCExtension {
// Call the start up config extensions. These may rely on the standard elements // Call the start up config extensions. These may rely on the standard elements
// having already been loaded so we wait to call them from here. // having already been loaded so we wait to call them from here.
if (startUpConfigElements != null) { if (startUpConfigElements != null) {
buildDefStartupList = new ArrayList<>( buildDefStartupList = new ArrayList<>(startUpConfigElements.size());
startUpConfigElements.size());
for (IManagedConfigElement startUpConfigElement : startUpConfigElements) { for (IManagedConfigElement startUpConfigElement : startUpConfigElements) {
IManagedBuildDefinitionsStartup customConfigLoader; IManagedBuildDefinitionsStartup customConfigLoader;

View file

@ -1466,8 +1466,7 @@ public class Configuration extends BuildObject implements IConfiguration, IBuild
ICSettingEntry[] libs = CDataUtil.resolveEntries(unresolved, des); ICSettingEntry[] libs = CDataUtil.resolveEntries(unresolved, des);
if (libs.length > 0) { if (libs.length > 0) {
for (ICExternalSetting setting : des.getExternalSettings()) { for (ICExternalSetting setting : des.getExternalSettings()) {
Set<ICSettingEntry> entries = new LinkedHashSet<>( Set<ICSettingEntry> entries = new LinkedHashSet<>(Arrays.asList(setting.getEntries()));
Arrays.asList(setting.getEntries()));
for (ICSettingEntry lib : libs) { for (ICSettingEntry lib : libs) {
if (entries.contains(lib)) { if (entries.contains(lib)) {
entries.remove(lib); entries.remove(lib);

View file

@ -91,8 +91,7 @@ public class HeadlessBuilderExternalSettingsProvider extends CExternalSettingPro
if (desc == null) if (desc == null)
continue; continue;
for (ICConfigurationDescription cfg : desc.getConfigurations()) { for (ICConfigurationDescription cfg : desc.getConfigurations()) {
ArrayList<String> extSettingIds = new ArrayList<>( ArrayList<String> extSettingIds = new ArrayList<>(Arrays.asList(cfg.getExternalSettingsProviderIds()));
Arrays.asList(cfg.getExternalSettingsProviderIds()));
for (Iterator<String> it = extSettingIds.iterator(); it.hasNext();) for (Iterator<String> it = extSettingIds.iterator(); it.hasNext();)
if (ID.equals(it.next())) if (ID.equals(it.next()))
it.remove(); it.remove();

View file

@ -296,8 +296,7 @@ public class Option extends BuildObject implements IOption, IBuildPropertiesRest
case UNDEF_MACRO_FILES: case UNDEF_MACRO_FILES:
if (option.value != null) { if (option.value != null) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
ArrayList<OptionStringValue> list = new ArrayList<>( ArrayList<OptionStringValue> list = new ArrayList<>((ArrayList<OptionStringValue>) option.value);
(ArrayList<OptionStringValue>) option.value);
value = list; value = list;
} }
if (option.defaultValue != null) { if (option.defaultValue != null) {

View file

@ -254,8 +254,7 @@ public class BuildEntryStorage extends AbstractEntryStorage {
} else { } else {
// If resolved, add each resolved entry as a separate UserEntryInfo // If resolved, add each resolved entry as a separate UserEntryInfo
boolean isMultiple = rVes.length > 1; boolean isMultiple = rVes.length > 1;
List<UserEntryInfo> sequense = isMultiple ? new ArrayList<>(rVes.length) List<UserEntryInfo> sequense = isMultiple ? new ArrayList<>(rVes.length) : null;
: null;
for (OptionStringValue rVe : rVes) { for (OptionStringValue rVe : rVes) {
ICLanguageSettingEntry entry = createUserEntry(option, rVe, flags, subst); ICLanguageSettingEntry entry = createUserEntry(option, rVe, flags, subst);
entryList.add(new UserEntryInfo(entry, ve, rVe, sequense)); entryList.add(new UserEntryInfo(entry, ve, rVe, sequense));

View file

@ -113,8 +113,7 @@ public class PathComparator implements Comparator<IPath> {
//all children //all children
SortedMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> children = getChildPathMap(map, path, false, SortedMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> children = getChildPathMap(map, path, false,
false); false);
SortedMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>( SortedMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>(INSTANCE);
INSTANCE);
for (Iterator<Map.Entry<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>>> iter = children.entrySet() for (Iterator<Map.Entry<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>>> iter = children.entrySet()
.iterator(); iter.hasNext(); iter = children.entrySet().iterator()) { .iterator(); iter.hasNext(); iter = children.entrySet().iterator()) {
Map.Entry<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> entry = iter.next(); Map.Entry<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> entry = iter.next();

View file

@ -213,8 +213,7 @@ public class TcModificationUtil {
int[] types = new int[] { IRealBuildObjectAssociation.OBJECT_TOOLCHAIN, int[] types = new int[] { IRealBuildObjectAssociation.OBJECT_TOOLCHAIN,
IRealBuildObjectAssociation.OBJECT_BUILDER, IRealBuildObjectAssociation.OBJECT_TOOL, }; IRealBuildObjectAssociation.OBJECT_BUILDER, IRealBuildObjectAssociation.OBJECT_TOOL, };
TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>( TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>(PathComparator.INSTANCE);
PathComparator.INSTANCE);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> clone = (TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>>) initialMap TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> clone = (TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>>) initialMap
.clone(); .clone();
@ -572,8 +571,7 @@ public class TcModificationUtil {
public static TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> createPathMap( public static TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> createPathMap(
PerTypeMapStorage<IRealBuildObjectAssociation, Set<IPath>> storage) { PerTypeMapStorage<IRealBuildObjectAssociation, Set<IPath>> storage) {
int[] types = ObjectTypeBasedStorage.getSupportedObjectTypes(); int[] types = ObjectTypeBasedStorage.getSupportedObjectTypes();
TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>( TreeMap<IPath, PerTypeSetStorage<IRealBuildObjectAssociation>> result = new TreeMap<>(PathComparator.INSTANCE);
PathComparator.INSTANCE);
for (int i = 0; i < types.length; i++) { for (int i = 0; i < types.length; i++) {
int type = types[i]; int type = types[i];
Map<IRealBuildObjectAssociation, Set<IPath>> map = storage.getMap(type, false); Map<IRealBuildObjectAssociation, Set<IPath>> map = storage.getMap(type, false);

View file

@ -247,8 +247,7 @@ public abstract class ToolListModification implements IToolListModification {
fOperations = new ModificationOperation[0]; fOperations = new ModificationOperation[0];
} }
} else { } else {
List<ModificationOperation> opList = new ArrayList<>( List<ModificationOperation> opList = new ArrayList<>(fCompatibleTools.size() + 1);
fCompatibleTools.size() + 1);
Set<Tool> keySet = fCompatibleTools.keySet(); Set<Tool> keySet = fCompatibleTools.keySet();
for (Tool tool : keySet) { for (Tool tool : keySet) {
if (tool == fRealTool) if (tool == fRealTool)

View file

@ -183,8 +183,8 @@ public class CodanCorePlugin extends Plugin {
if (bundle != null) { if (bundle != null) {
BundleContext context = bundle.getBundleContext(); BundleContext context = bundle.getBundleContext();
if (context != null) { if (context != null) {
ServiceTracker<DebugOptions, DebugOptions> tracker = new ServiceTracker<>( ServiceTracker<DebugOptions, DebugOptions> tracker = new ServiceTracker<>(context,
context, DebugOptions.class.getName(), null); DebugOptions.class.getName(), null);
try { try {
tracker.open(); tracker.open();
debugOptions = tracker.getService(); debugOptions = tracker.getService();

View file

@ -534,16 +534,14 @@ public class LanguageSettingsListenersTests extends BaseTestCase {
// add global provider which is not engaged // add global provider which is not engaged
ILanguageSettingsProvider provider = new MockListenerRegisterer(PROVIDER_CUSTOM_GLOBAL, ILanguageSettingsProvider provider = new MockListenerRegisterer(PROVIDER_CUSTOM_GLOBAL,
PROVIDER_CUSTOM_GLOBAL_NAME); PROVIDER_CUSTOM_GLOBAL_NAME);
List<ILanguageSettingsProvider> providers = new ArrayList<>( List<ILanguageSettingsProvider> providers = new ArrayList<>(workspaceProvidersOriginal);
workspaceProvidersOriginal);
providers.add(provider); providers.add(provider);
LanguageSettingsManager.setWorkspaceProviders(providers); LanguageSettingsManager.setWorkspaceProviders(providers);
assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL)); assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL));
} }
{ {
// remove global provider and restore original list // remove global provider and restore original list
List<ILanguageSettingsProvider> providers = new ArrayList<>( List<ILanguageSettingsProvider> providers = new ArrayList<>(workspaceProvidersOriginal);
workspaceProvidersOriginal);
LanguageSettingsManager.setWorkspaceProviders(providers); LanguageSettingsManager.setWorkspaceProviders(providers);
assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL)); assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL));
} }
@ -601,8 +599,7 @@ public class LanguageSettingsListenersTests extends BaseTestCase {
} }
{ {
// remove global provider // remove global provider
List<ILanguageSettingsProvider> providers = new ArrayList<>( List<ILanguageSettingsProvider> providers = new ArrayList<>(workspaceProvidersOriginal);
workspaceProvidersOriginal);
LanguageSettingsManager.setWorkspaceProviders(providers); LanguageSettingsManager.setWorkspaceProviders(providers);
assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL)); assertEquals(0, MockListenerRegisterer.getCount(PROVIDER_CUSTOM_GLOBAL));
} }

View file

@ -598,8 +598,7 @@ public class CProjectDescriptionDeltaTests extends BaseTestCase {
assertNotNull(cfgDescription); assertNotNull(cfgDescription);
// Modification SOURCE_ADDED // Modification SOURCE_ADDED
List<ICSourceEntry> sourceEntries = new ArrayList<>( List<ICSourceEntry> sourceEntries = new ArrayList<>(Arrays.asList(cfgDescription.getSourceEntries()));
Arrays.asList(cfgDescription.getSourceEntries()));
ICSourceEntry testSourceEntry = new CSourceEntry(project.getFullPath().append("test_src"), null, ICSourceEntry testSourceEntry = new CSourceEntry(project.getFullPath().append("test_src"), null,
ICSettingEntry.RESOLVED); ICSettingEntry.RESOLVED);
sourceEntries.add(testSourceEntry); sourceEntries.add(testSourceEntry);
@ -648,8 +647,7 @@ public class CProjectDescriptionDeltaTests extends BaseTestCase {
ICConfigurationDescription cfgDescription = prjDescription.getConfigurations()[0]; ICConfigurationDescription cfgDescription = prjDescription.getConfigurations()[0];
assertNotNull(cfgDescription); assertNotNull(cfgDescription);
List<ICSourceEntry> sourceEntries = new ArrayList<>( List<ICSourceEntry> sourceEntries = new ArrayList<>(Arrays.asList(cfgDescription.getSourceEntries()));
Arrays.asList(cfgDescription.getSourceEntries()));
sourceEntries.add(testSourceEntry); sourceEntries.add(testSourceEntry);
cfgDescription.setSourceEntries(sourceEntries.toArray(new ICSourceEntry[0])); cfgDescription.setSourceEntries(sourceEntries.toArray(new ICSourceEntry[0]));

View file

@ -244,8 +244,7 @@ public class ProjectLanguageConfiguration {
* @param file * @param file
*/ */
public void setFileMappings(IFile file, Map<String, String> mappings) { public void setFileMappings(IFile file, Map<String, String> mappings) {
fFileConfigurationMappings.put(file.getProjectRelativePath().toPortableString(), fFileConfigurationMappings.put(file.getProjectRelativePath().toPortableString(), new TreeMap<>(mappings));
new TreeMap<>(mappings));
} }
private Map<String, Map<String, String>> copyLanguageMappings(Map<String, Map<String, String>> mappings, private Map<String, Map<String, String>> copyLanguageMappings(Map<String, Map<String, String>> mappings,

View file

@ -1208,8 +1208,7 @@ public class LanguageSettingsProvidersSerializer {
String[] ids = ((ILanguageSettingsProvidersKeeper) cfgDescription) String[] ids = ((ILanguageSettingsProvidersKeeper) cfgDescription)
.getDefaultLanguageSettingsProvidersIds(); .getDefaultLanguageSettingsProvidersIds();
if (ids != null) { if (ids != null) {
List<ILanguageSettingsProvider> providers = new ArrayList<>( List<ILanguageSettingsProvider> providers = new ArrayList<>(ids.length);
ids.length);
for (String id : ids) { for (String id : ids) {
if (LanguageSettingsExtensionManager.isPreferShared(id)) { if (LanguageSettingsExtensionManager.isPreferShared(id)) {
providers.add(LanguageSettingsManager.getWorkspaceProvider(id)); providers.add(LanguageSettingsManager.getWorkspaceProvider(id));

View file

@ -190,8 +190,7 @@ public class XmlProjectDescriptionStorage extends AbstractCProjectDescriptionSto
/** A soft reference to the read-only project description /** A soft reference to the read-only project description
* Volatile provides a memory barrier in Java 5+ */ * Volatile provides a memory barrier in Java 5+ */
private volatile Reference<ICProjectDescription> fProjectDescription = new SoftReference<>( private volatile Reference<ICProjectDescription> fProjectDescription = new SoftReference<>(null);
null);
/** The last modification stamp of the .cproject project description file */ /** The last modification stamp of the .cproject project description file */
private volatile long projectModificaitonStamp = IResource.NULL_STAMP; private volatile long projectModificaitonStamp = IResource.NULL_STAMP;

View file

@ -153,8 +153,7 @@ public class ExternalExportProjectProvider extends AbstractExportProjectProvider
content.createLink(new Path(location.getAbsolutePath()), IResource.NONE, null); content.createLink(new Path(location.getAbsolutePath()), IResource.NONE, null);
// Setup path entries // Setup path entries
List<IPathEntry> entries = new ArrayList<>( List<IPathEntry> entries = new ArrayList<>(Arrays.asList(CoreModel.getRawPathEntries(cproject)));
Arrays.asList(CoreModel.getRawPathEntries(cproject)));
// pre-include files // pre-include files
for (String path : includeFiles) { for (String path : includeFiles) {

View file

@ -152,8 +152,7 @@ public class Profiler {
} }
if (!profiler.counters.isEmpty()) { if (!profiler.counters.isEmpty()) {
List<Map.Entry<String, int[]>> keyList = new ArrayList<>( List<Map.Entry<String, int[]>> keyList = new ArrayList<>(profiler.counters.entrySet());
profiler.counters.entrySet());
Comparator<Map.Entry<String, int[]>> c2 = new Comparator<Map.Entry<String, int[]>>() { Comparator<Map.Entry<String, int[]>> c2 = new Comparator<Map.Entry<String, int[]>>() {
@Override @Override
public int compare(Entry<String, int[]> o1, Entry<String, int[]> o2) { public int compare(Entry<String, int[]> o1, Entry<String, int[]> o2) {

View file

@ -256,8 +256,7 @@ public class UserDefinedEnvironmentSupplier extends StorableEnvironmentLoader
private IEnvironmentVariable[] combineVariables(IEnvironmentVariable[] oldVariables, private IEnvironmentVariable[] combineVariables(IEnvironmentVariable[] oldVariables,
IEnvironmentVariable[] newVariables) { IEnvironmentVariable[] newVariables) {
Map<String, IEnvironmentVariable> vars = new HashMap<>( Map<String, IEnvironmentVariable> vars = new HashMap<>(oldVariables.length + newVariables.length);
oldVariables.length + newVariables.length);
for (IEnvironmentVariable variable : oldVariables) for (IEnvironmentVariable variable : oldVariables)
vars.put(variable.getName(), variable); vars.put(variable.getName(), variable);
for (IEnvironmentVariable variable : newVariables) { for (IEnvironmentVariable variable : newVariables) {

View file

@ -131,8 +131,7 @@ public class FoldingTest extends FoldingTestBase {
} }
private void assertNoKeyCollisions() { private void assertNoKeyCollisions() {
ProjectionAnnotationModel model = fEditor ProjectionAnnotationModel model = fEditor.getAdapter(ProjectionAnnotationModel.class);
.getAdapter(ProjectionAnnotationModel.class);
assertNotNull(model); assertNotNull(model);
int annotations = 0; int annotations = 0;
Set<Object> keys = new HashSet<>(); Set<Object> keys = new HashSet<>();

View file

@ -253,8 +253,7 @@ abstract public class FoldingTestBase extends BaseUITestCase {
protected PositionAndCollapsed[] getFoldingPositions() { protected PositionAndCollapsed[] getFoldingPositions() {
List<PositionAndCollapsed> positionAndCollapseds = new ArrayList<>(); List<PositionAndCollapsed> positionAndCollapseds = new ArrayList<>();
ProjectionAnnotationModel model = fEditor ProjectionAnnotationModel model = fEditor.getAdapter(ProjectionAnnotationModel.class);
.getAdapter(ProjectionAnnotationModel.class);
assertNotNull(model); assertNotNull(model);
for (Iterator<Annotation> iter = model.getAnnotationIterator(); iter.hasNext();) { for (Iterator<Annotation> iter = model.getAnnotationIterator(); iter.hasNext();) {
Annotation ann = iter.next(); Annotation ann = iter.next();

View file

@ -1344,8 +1344,7 @@ public class CEditor extends TextEditor
* AST reconciling listeners. * AST reconciling listeners.
* @since 4.0 * @since 4.0
*/ */
private final ListenerList<ICReconcilingListener> fReconcilingListeners = new ListenerList<>( private final ListenerList<ICReconcilingListener> fReconcilingListeners = new ListenerList<>(ListenerList.IDENTITY);
ListenerList.IDENTITY);
/** /**
* Semantic highlighting manager * Semantic highlighting manager

View file

@ -57,8 +57,7 @@ class EclipsePreferencesAdapter implements IPreferenceStore {
} }
/** Listeners on on this adapter */ /** Listeners on on this adapter */
private ListenerList<IPropertyChangeListener> fListeners = new ListenerList<>( private ListenerList<IPropertyChangeListener> fListeners = new ListenerList<>(ListenerList.IDENTITY);
ListenerList.IDENTITY);
/** Listener on the node */ /** Listener on the node */
private IEclipsePreferences.IPreferenceChangeListener fListener = new PreferenceChangeListener(); private IEclipsePreferences.IPreferenceChangeListener fListener = new PreferenceChangeListener();

View file

@ -253,8 +253,7 @@ public class ProjectLanguageMappingWidget extends LanguageMappingWidget {
} }
if (fChild != null) { if (fChild != null) {
Set<String> overrides = new HashSet<>( Set<String> overrides = new HashSet<>(createWorkspaceContentTypeFilter(fConfigurationContentTypeMappings));
createWorkspaceContentTypeFilter(fConfigurationContentTypeMappings));
fChild.setOverriddenContentTypes(overrides); fChild.setOverriddenContentTypes(overrides);
fChild.refreshMappings(); fChild.refreshMappings();
} }

View file

@ -1190,8 +1190,7 @@ public class LanguageSettingsEntriesTab extends AbstractCPropertyTab {
IResource rc = getResource(); IResource rc = getResource();
List<ILanguageSettingsProvider> oldProviders = ((ILanguageSettingsProvidersKeeper) cfgDescription) List<ILanguageSettingsProvider> oldProviders = ((ILanguageSettingsProvidersKeeper) cfgDescription)
.getLanguageSettingProviders(); .getLanguageSettingProviders();
List<ILanguageSettingsProvider> newProviders = new ArrayList<>( List<ILanguageSettingsProvider> newProviders = new ArrayList<>(oldProviders.size());
oldProviders.size());
// clear entries for a given resource for all languages where applicable // clear entries for a given resource for all languages where applicable
providers: for (ILanguageSettingsProvider provider : oldProviders) { providers: for (ILanguageSettingsProvider provider : oldProviders) {

View file

@ -74,8 +74,7 @@ abstract class AbstractWorkingSetConfigsContribution extends CompoundContributio
} }
// sort the configurations by name // sort the configurations by name
List<IWorkingSetConfiguration> configs = new java.util.ArrayList<>( List<IWorkingSetConfiguration> configs = new java.util.ArrayList<>(getWorkingSet().getConfigurations());
getWorkingSet().getConfigurations());
Collections.sort(configs, configOrdering); Collections.sort(configs, configOrdering);
IContributionItem[] result = new IContributionItem[configs.size()]; IContributionItem[] result = new IContributionItem[configs.size()];

View file

@ -210,8 +210,7 @@ public interface IWorkingSetProjectConfigurationFactory {
// first pass to populate the map with immediate requireds // first pass to populate the map with immediate requireds
IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspace ws = ResourcesPlugin.getWorkspace();
for (IProjectNatureDescriptor next : ws.getNatureDescriptors()) { for (IProjectNatureDescriptor next : ws.getNatureDescriptors()) {
result.put(next.getNatureId(), result.put(next.getNatureId(), new java.util.HashSet<>(Arrays.asList(next.getRequiredNatureIds())));
new java.util.HashSet<>(Arrays.asList(next.getRequiredNatureIds())));
} }
// now, iterate to add transitive requireds // now, iterate to add transitive requireds

View file

@ -181,8 +181,7 @@ public class WorkingSetConfiguration implements IWorkingSetConfiguration {
public IStatus build(IProgressMonitor monitor) { public IStatus build(IProgressMonitor monitor) {
MultiStatus result = new MultiStatus(CUIPlugin.PLUGIN_ID, 0, WorkingSetMessages.WSConfig_build_problems, null); MultiStatus result = new MultiStatus(CUIPlugin.PLUGIN_ID, 0, WorkingSetMessages.WSConfig_build_problems, null);
List<IWorkingSetProjectConfiguration> toBuild = new java.util.ArrayList<>( List<IWorkingSetProjectConfiguration> toBuild = new java.util.ArrayList<>(getProjectConfigurations().size());
getProjectConfigurations().size());
for (IWorkingSetProjectConfiguration next : getProjectConfigurations()) { for (IWorkingSetProjectConfiguration next : getProjectConfigurations()) {
IProject project = next.resolveProject(); IProject project = next.resolveProject();

View file

@ -89,8 +89,7 @@ public class CHelpConfigurationPropertyPage extends PropertyPage implements IWor
/* 0 */ CUIMessages.CHelpConfigurationPropertyPage_buttonLabels_CheckAll, /* 0 */ CUIMessages.CHelpConfigurationPropertyPage_buttonLabels_CheckAll,
/* 1 */ CUIMessages.CHelpConfigurationPropertyPage_buttonLabels_UncheckAll }; /* 1 */ CUIMessages.CHelpConfigurationPropertyPage_buttonLabels_UncheckAll };
fCHelpBookList = new CheckedListDialogField<>(null, buttonLabels, fCHelpBookList = new CheckedListDialogField<>(null, buttonLabels, new CHelpBookListLabelProvider());
new CHelpBookListLabelProvider());
fCHelpBookList.setLabelText(CUIMessages.CHelpConfigurationPropertyPage_HelpBooks); fCHelpBookList.setLabelText(CUIMessages.CHelpConfigurationPropertyPage_HelpBooks);
fCHelpBookList.setCheckAllButtonIndex(0); fCHelpBookList.setCheckAllButtonIndex(0);
fCHelpBookList.setUncheckAllButtonIndex(1); fCHelpBookList.setUncheckAllButtonIndex(1);

View file

@ -81,8 +81,7 @@ public class TemplateClassWizard extends TemplatesChoiceWizard implements INewWi
@Override @Override
public Template[] getTemplates() { public Template[] getTemplates() {
SortedSet<TemplateCore> templateList = new TreeSet<>( SortedSet<TemplateCore> templateList = new TreeSet<>(TemplateCore.TEMPLATE_ID_CASE_INSENSITIVE_COMPARATOR);
TemplateCore.TEMPLATE_ID_CASE_INSENSITIVE_COMPARATOR);
templateList.addAll(Arrays.asList(TemplateEngineUI.getDefault().getTemplates())); templateList.addAll(Arrays.asList(TemplateEngineUI.getDefault().getTemplates()));
return templateList.toArray(new Template[templateList.size()]); return templateList.toArray(new Template[templateList.size()]);
} }

View file

@ -100,7 +100,6 @@ public class TemplateInputDialog extends Dialog {
setShellStyle(getShellStyle() | SWT.RESIZE); setShellStyle(getShellStyle() | SWT.RESIZE);
} }
@Override @Override
protected void configureShell(Shell shell) { protected void configureShell(Shell shell) {
super.configureShell(shell); super.configureShell(shell);
@ -108,7 +107,6 @@ public class TemplateInputDialog extends Dialog {
display = shell.getDisplay(); display = shell.getDisplay();
} }
@Override @Override
protected Control createDialogArea(Composite parent) { protected Control createDialogArea(Composite parent) {
@ -216,7 +214,6 @@ public class TemplateInputDialog extends Dialog {
aText.addModifyListener(mListener); aText.addModifyListener(mListener);
} }
@Override @Override
protected void okPressed() { protected void okPressed() {
if (option == TemplatePreferencePage.OPTION_ADD) { if (option == TemplatePreferencePage.OPTION_ADD) {

View file

@ -127,8 +127,8 @@ public class Trace {
if (bundle != null) { if (bundle != null) {
BundleContext context = bundle.getBundleContext(); BundleContext context = bundle.getBundleContext();
if (context != null) { if (context != null) {
ServiceTracker<DebugOptions, DebugOptions> tracker = new ServiceTracker<>( ServiceTracker<DebugOptions, DebugOptions> tracker = new ServiceTracker<>(context,
context, DebugOptions.class.getName(), null); DebugOptions.class.getName(), null);
try { try {
tracker.open(); tracker.open();
DebugOptions debugOptions = tracker.getService(); DebugOptions debugOptions = tracker.getService();

View file

@ -313,8 +313,7 @@ public class CSourceNotFoundEditor extends CommonSourceNotFoundEditor {
private void addSourceMappingToDirector(String missingPath, IPath newSourcePath, private void addSourceMappingToDirector(String missingPath, IPath newSourcePath,
AbstractSourceLookupDirector director) throws CoreException { AbstractSourceLookupDirector director) throws CoreException {
ArrayList<ISourceContainer> containerList = new ArrayList<>( ArrayList<ISourceContainer> containerList = new ArrayList<>(Arrays.asList(director.getSourceContainers()));
Arrays.asList(director.getSourceContainers()));
MappingSourceContainer foundMappings = null; MappingSourceContainer foundMappings = null;
for (ISourceContainer container : containerList) { for (ISourceContainer container : containerList) {
if (container instanceof MappingSourceContainer) { if (container instanceof MappingSourceContainer) {

View file

@ -77,8 +77,7 @@ public class SourceFilesViewer extends BaseViewer {
/** Tradeoff expensiveness of checking filesystem against likelihood /** Tradeoff expensiveness of checking filesystem against likelihood
* that files will be added/removed/changed in the given time period */ * that files will be added/removed/changed in the given time period */
static final long FILE_CHECK_DELTA = 30 * 1000; static final long FILE_CHECK_DELTA = 30 * 1000;
private static LRUCache<Object, TranslationUnitInfo> translationUnitInfoCache = new LRUCache<>( private static LRUCache<Object, TranslationUnitInfo> translationUnitInfoCache = new LRUCache<>(1024);
1024);
public SourceFilesViewer(ExecutablesView view, Composite parent, int style) { public SourceFilesViewer(ExecutablesView view, Composite parent, int style) {
super(view, parent, style); super(view, parent, style);

View file

@ -662,8 +662,7 @@ public class GDBPatternMatchingExpressions extends AbstractDsfService implements
// Not only does selecting the element jump back and forth between the duplicates, // Not only does selecting the element jump back and forth between the duplicates,
// but children of duplicated elements are not always right. Because of this, we // but children of duplicated elements are not always right. Because of this, we
// remove all duplicates here. // remove all duplicates here.
LinkedHashSet<IExpressionDMContext> uniqueSubExprSet = new LinkedHashSet<>( LinkedHashSet<IExpressionDMContext> uniqueSubExprSet = new LinkedHashSet<>(subExprList);
subExprList);
subExprList.clear(); subExprList.clear();
subExprList.addAll(uniqueSubExprSet); subExprList.addAll(uniqueSubExprSet);
@ -776,8 +775,7 @@ public class GDBPatternMatchingExpressions extends AbstractDsfService implements
matchArrays(exprDmc, new ImmediateDataRequestMonitor<List<IExpressionDMContext>>(rm) { matchArrays(exprDmc, new ImmediateDataRequestMonitor<List<IExpressionDMContext>>(rm) {
@Override @Override
protected void handleSuccess() { protected void handleSuccess() {
final List<IExpressionDMContext> exprList = getData() != null ? getData() final List<IExpressionDMContext> exprList = getData() != null ? getData() : new ArrayList<>();
: new ArrayList<>();
matchLocals(exprDmc, new ImmediateDataRequestMonitor<List<IExpressionDMContext>>(rm) { matchLocals(exprDmc, new ImmediateDataRequestMonitor<List<IExpressionDMContext>>(rm) {
@Override @Override
protected void handleSuccess() { protected void handleSuccess() {
@ -865,8 +863,7 @@ public class GDBPatternMatchingExpressions extends AbstractDsfService implements
final CountingRequestMonitor varNameCRM = new CountingRequestMonitor(getExecutor(), rm) { final CountingRequestMonitor varNameCRM = new CountingRequestMonitor(getExecutor(), rm) {
@Override @Override
public void handleSuccess() { public void handleSuccess() {
ArrayList<IExpressionDMContext> matches = new ArrayList<>( ArrayList<IExpressionDMContext> matches = new ArrayList<>(localsDMData.length);
localsDMData.length);
String fullExpr = globDmc.getExpression().trim(); String fullExpr = globDmc.getExpression().trim();
if (fullExpr.startsWith(GLOB_EXPRESSION_PREFIX)) { if (fullExpr.startsWith(GLOB_EXPRESSION_PREFIX)) {

View file

@ -2595,8 +2595,7 @@ public class GDBRunControl_7_0_NS extends AbstractDsfService
Set<IExecutionDMContext> specifiedExedDmcSet = new HashSet<>(Arrays.asList(contexts)); Set<IExecutionDMContext> specifiedExedDmcSet = new HashSet<>(Arrays.asList(contexts));
// A list that ignores threads for which the process is also present // A list that ignores threads for which the process is also present
List<IExecutionDMContext> execDmcForOperationList = new ArrayList<>( List<IExecutionDMContext> execDmcForOperationList = new ArrayList<>(specifiedExedDmcSet.size());
specifiedExedDmcSet.size());
// Check for the case of a process selected along with some of its threads // Check for the case of a process selected along with some of its threads
for (IExecutionDMContext execDmc : specifiedExedDmcSet) { for (IExecutionDMContext execDmc : specifiedExedDmcSet) {

View file

@ -170,8 +170,7 @@ public class SyncUtil {
public static MIStoppedEvent step(final IExecutionDMContext dmc, final StepType stepType, boolean reverse, public static MIStoppedEvent step(final IExecutionDMContext dmc, final StepType stepType, boolean reverse,
int massagedTimeout) throws Throwable { int massagedTimeout) throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
if (!reverse) { if (!reverse) {
fRunControl.getExecutor().submit(new Runnable() { fRunControl.getExecutor().submit(new Runnable() {
@ -280,8 +279,7 @@ public class SyncUtil {
private static MIStoppedEvent resumeUntilStopped(final IExecutionDMContext dmc, int massagedTimeout) private static MIStoppedEvent resumeUntilStopped(final IExecutionDMContext dmc, int massagedTimeout)
throws Throwable { throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
fRunControl.getExecutor().submit(new Runnable() { fRunControl.getExecutor().submit(new Runnable() {
@Override @Override
@ -308,8 +306,7 @@ public class SyncUtil {
} }
public static MIRunningEvent resume(final IExecutionDMContext dmc, int massagedTimeout) throws Throwable { public static MIRunningEvent resume(final IExecutionDMContext dmc, int massagedTimeout) throws Throwable {
final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIRunningEvent.class);
MIRunningEvent.class);
fRunControl.getExecutor().submit(new Runnable() { fRunControl.getExecutor().submit(new Runnable() {
@Override @Override
@ -378,8 +375,7 @@ public class SyncUtil {
// if there is a sleep in the code between the resume and the time // if there is a sleep in the code between the resume and the time
// it stops; this will give us plenty of time to call this method. // it stops; this will give us plenty of time to call this method.
public static MIStoppedEvent waitForStop(int timeout) throws Throwable { public static MIStoppedEvent waitForStop(int timeout) throws Throwable {
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
// Wait for the execution to suspend // Wait for the execution to suspend
return eventWaitor.waitForEvent(TestsPlugin.massageTimeout(timeout)); return eventWaitor.waitForEvent(TestsPlugin.massageTimeout(timeout));
@ -778,8 +774,7 @@ public class SyncUtil {
} }
// Now wait for the stopped event of the restart // Now wait for the stopped event of the restart
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
// Perform the restart // Perform the restart
Query<IContainerDMContext> query2 = new Query<IContainerDMContext>() { Query<IContainerDMContext> query2 = new Query<IContainerDMContext>() {

View file

@ -97,8 +97,8 @@ public class CommandTimeoutTest extends BaseParametrizedTestCase {
doLaunch(); doLaunch();
final DsfSession session = getGDBLaunch().getSession(); final DsfSession session = getGDBLaunch().getSession();
ServiceEventWaitor<ICommandControlShutdownDMEvent> shutdownEventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<ICommandControlShutdownDMEvent> shutdownEventWaitor = new ServiceEventWaitor<>(session,
session, ICommandControlShutdownDMEvent.class); ICommandControlShutdownDMEvent.class);
// Send the command that will timeout // Send the command that will timeout
Query<MIInfo> query = new Query<MIInfo>() { Query<MIInfo> query = new Query<MIInfo>() {

View file

@ -714,8 +714,7 @@ public class LaunchConfigurationAndRestartTest extends BaseParametrizedTestCase
// Now step backwards to make sure reverse was enabled // Now step backwards to make sure reverse was enabled
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
final int REVERSE_NUM_STEPS = 2; final int REVERSE_NUM_STEPS = 2;
final IExecutionDMContext execDmc = stoppedEvent.getDMContext(); final IExecutionDMContext execDmc = stoppedEvent.getDMContext();
@ -780,8 +779,7 @@ public class LaunchConfigurationAndRestartTest extends BaseParametrizedTestCase
frame.getFunction().equals("stopAtOther")); frame.getFunction().equals("stopAtOther"));
// Now step backwards all the way to the start to make sure reverse was enabled from the very start // Now step backwards all the way to the start to make sure reverse was enabled from the very start
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
final int REVERSE_NUM_STEPS = 3; final int REVERSE_NUM_STEPS = 3;
Query<MIInfo> query2 = new Query<MIInfo>() { Query<MIInfo> query2 = new Query<MIInfo>() {
@ -854,8 +852,7 @@ public class LaunchConfigurationAndRestartTest extends BaseParametrizedTestCase
frame.getFunction().equals("main") && frame.getLine() == LAST_LINE_IN_MAIN); frame.getFunction().equals("main") && frame.getLine() == LAST_LINE_IN_MAIN);
// Now step backwards all the way to the start to make sure reverse was enabled from the very start // Now step backwards all the way to the start to make sure reverse was enabled from the very start
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fSession, MIStoppedEvent.class);
MIStoppedEvent.class);
final int REVERSE_NUM_STEPS = 3; final int REVERSE_NUM_STEPS = 3;
Query<MIInfo> query2 = new Query<MIInfo>() { Query<MIInfo> query2 = new Query<MIInfo>() {

View file

@ -1302,8 +1302,7 @@ public class MICatchpointsTest extends BaseParametrizedTestCase {
assertEquals("Unexpected number of breakpoint-added events", 1, getBreakpointEventCount(BP_ADDED)); assertEquals("Unexpected number of breakpoint-added events", 1, getBreakpointEventCount(BP_ADDED));
// Ensure the breakpoint service sees what we expect // Ensure the breakpoint service sees what we expect
List<IBreakpointDMContext> bkptsAfter = new LinkedList<>( List<IBreakpointDMContext> bkptsAfter = new LinkedList<>(Arrays.asList(getBreakpoints(fBreakpointsDmc)));
Arrays.asList(getBreakpoints(fBreakpointsDmc)));
assertEquals("Breakpoints service reports unexpected number of breakpoints", bkptsBefore.length + 1, assertEquals("Breakpoints service reports unexpected number of breakpoints", bkptsBefore.length + 1,
bkptsAfter.size()); bkptsAfter.size());
@ -1361,8 +1360,7 @@ public class MICatchpointsTest extends BaseParametrizedTestCase {
// Ensure the breakpoint service sees what we expect. Ask the breakpoint // Ensure the breakpoint service sees what we expect. Ask the breakpoint
// service for the list of breakpoint against and make sure it differs // service for the list of breakpoint against and make sure it differs
// only by the newly added one // only by the newly added one
List<IBreakpointDMContext> bkptsAfter = new LinkedList<>( List<IBreakpointDMContext> bkptsAfter = new LinkedList<>(Arrays.asList(getBreakpoints(fBreakpointsDmc)));
Arrays.asList(getBreakpoints(fBreakpointsDmc)));
assertEquals("Breakpoints service reports unexpected number of breakpoints", bkptsBefore.length + 1, assertEquals("Breakpoints service reports unexpected number of breakpoints", bkptsBefore.length + 1,
bkptsAfter.size()); bkptsAfter.size());
ListIterator<IBreakpointDMContext> iter = bkptsAfter.listIterator(); ListIterator<IBreakpointDMContext> iter = bkptsAfter.listIterator();

View file

@ -224,8 +224,8 @@ public class MIModifiedServicesTest extends BaseParametrizedTestCase {
private void resumeContainerContextExe() throws InterruptedException, ExecutionException, TimeoutException { private void resumeContainerContextExe() throws InterruptedException, ExecutionException, TimeoutException {
final ServiceEventWaitor<IResumedDMEvent> resumedWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<IResumedDMEvent> resumedWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(),
getGDBLaunch().getSession(), IResumedDMEvent.class); IResumedDMEvent.class);
Query<Void> query = new Query<Void>() { Query<Void> query = new Query<Void>() {
@Override @Override

View file

@ -413,8 +413,8 @@ public class MIRegistersTest extends BaseParametrizedTestCase {
*/ */
private List<IRegistersChangedDMEvent> writeRegisterWaitNotication(final IRegisterDMContext registerDmc, private List<IRegistersChangedDMEvent> writeRegisterWaitNotication(final IRegisterDMContext registerDmc,
final String regValue, final String formatId) throws Throwable { final String regValue, final String formatId) throws Throwable {
ServiceEventWaitor<IRegistersChangedDMEvent> eventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<IRegistersChangedDMEvent> eventWaitor = new ServiceEventWaitor<>(fSession,
fSession, IRegistersChangedDMEvent.class); IRegistersChangedDMEvent.class);
writeRegister(registerDmc, regValue, formatId); writeRegister(registerDmc, regValue, formatId);

View file

@ -372,8 +372,7 @@ public class MIRunControlTargetAvailableTest extends BaseParametrizedTestCase {
// Wait up to 3 second for the target to suspend. Should happen within two seconds. // Wait up to 3 second for the target to suspend. Should happen within two seconds.
suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000)); suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000));
suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
SyncUtil.resume(); SyncUtil.resume();
@ -575,8 +574,7 @@ public class MIRunControlTargetAvailableTest extends BaseParametrizedTestCase {
suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000)); suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000));
// Now resume the target and check that we stop at all the breakpoints. // Now resume the target and check that we stop at all the breakpoints.
suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
SyncUtil.resume(); SyncUtil.resume();
} }
@ -707,8 +705,7 @@ public class MIRunControlTargetAvailableTest extends BaseParametrizedTestCase {
suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000)); suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000));
// Now resume the target and check that we stop at all the breakpoints. // Now resume the target and check that we stop at all the breakpoints.
suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
SyncUtil.resume(); SyncUtil.resume();
} }
@ -835,8 +832,7 @@ public class MIRunControlTargetAvailableTest extends BaseParametrizedTestCase {
suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000)); suspendedEventWaitor.waitForEvent(TestsPlugin.massageTimeout(3000));
// Now resume the target and check that we stop at all the breakpoints. // Now resume the target and check that we stop at all the breakpoints.
suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), suspendedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(), ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
SyncUtil.resume(); SyncUtil.resume();
} }

View file

@ -580,8 +580,8 @@ public class MIRunControlTest extends BaseParametrizedTestCase {
//TestsPlugin.debug("handleCompleted over"); //TestsPlugin.debug("handleCompleted over");
} }
}; };
final ServiceEventWaitor<IResumedDMEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<IResumedDMEvent> eventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(),
getGDBLaunch().getSession(), IResumedDMEvent.class); IResumedDMEvent.class);
final IContainerDMContext containerDmc = SyncUtil.getContainerContext(); final IContainerDMContext containerDmc = SyncUtil.getContainerContext();
@ -629,8 +629,8 @@ public class MIRunControlTest extends BaseParametrizedTestCase {
} }
}; };
final ServiceEventWaitor<IResumedDMEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<IResumedDMEvent> eventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(),
getGDBLaunch().getSession(), IResumedDMEvent.class); IResumedDMEvent.class);
fRunCtrl.getExecutor().submit(new Runnable() { fRunCtrl.getExecutor().submit(new Runnable() {
@Override @Override

View file

@ -215,8 +215,8 @@ public class OperationsWhileTargetIsRunningTest extends BaseParametrizedTestCase
// then we terminate the process, and confirm that there are no more processes // then we terminate the process, and confirm that there are no more processes
SyncUtil.resume(); SyncUtil.resume();
ServiceEventWaitor<IExitedDMEvent> exitedEventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<IExitedDMEvent> exitedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(),
getGDBLaunch().getSession(), IExitedDMEvent.class); IExitedDMEvent.class);
Query<Object> query = new Query<Object>() { Query<Object> query = new Query<Object>() {
@Override @Override
@ -297,8 +297,8 @@ public class OperationsWhileTargetIsRunningTest extends BaseParametrizedTestCase
// then we detach the process, and confirm that we are not longer running // then we detach the process, and confirm that we are not longer running
SyncUtil.resume(); SyncUtil.resume();
ServiceEventWaitor<IExitedDMEvent> exitedEventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<IExitedDMEvent> exitedEventWaitor = new ServiceEventWaitor<>(getGDBLaunch().getSession(),
getGDBLaunch().getSession(), IExitedDMEvent.class); IExitedDMEvent.class);
Query<Object> query = new Query<Object>() { Query<Object> query = new Query<Object>() {
@Override @Override

View file

@ -353,8 +353,7 @@ public class SourceLookupTest extends BaseParametrizedTestCase {
protected void addSourceContainer(AbstractSourceLookupDirector director, ISourceContainer container) protected void addSourceContainer(AbstractSourceLookupDirector director, ISourceContainer container)
throws CoreException { throws CoreException {
ArrayList<ISourceContainer> containerList = new ArrayList<>( ArrayList<ISourceContainer> containerList = new ArrayList<>(Arrays.asList(director.getSourceContainers()));
Arrays.asList(director.getSourceContainers()));
container.init(director); container.init(director);
containerList.add(container); containerList.add(container);
director.setSourceContainers(containerList.toArray(new ISourceContainer[containerList.size()])); director.setSourceContainers(containerList.toArray(new ISourceContainer[containerList.size()]));

View file

@ -186,8 +186,7 @@ public class StepIntoSelectionTest extends BaseParametrizedTestCase {
*/ */
private ISuspendedDMEvent triggerStepIntoSelection(final IExecutionDMContext exeContext, final String sourceName, private ISuspendedDMEvent triggerStepIntoSelection(final IExecutionDMContext exeContext, final String sourceName,
final int targetLine, final IFunctionDeclaration function, final boolean skipBreakPoints) throws Throwable { final int targetLine, final IFunctionDeclaration function, final boolean skipBreakPoints) throws Throwable {
ServiceEventWaitor<ISuspendedDMEvent> eventWaitor = new ServiceEventWaitor<>(fSession, ServiceEventWaitor<ISuspendedDMEvent> eventWaitor = new ServiceEventWaitor<>(fSession, ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
Query<Object> query = new Query<Object>() { Query<Object> query = new Query<Object>() {
@Override @Override
@ -207,8 +206,7 @@ public class StepIntoSelectionTest extends BaseParametrizedTestCase {
*/ */
private ISuspendedDMEvent triggerRunToLine(final IExecutionDMContext exeContext, final String sourceName, private ISuspendedDMEvent triggerRunToLine(final IExecutionDMContext exeContext, final String sourceName,
final int targetLine, final boolean skipBreakPoints) throws Throwable { final int targetLine, final boolean skipBreakPoints) throws Throwable {
ServiceEventWaitor<ISuspendedDMEvent> eventWaitor = new ServiceEventWaitor<>(fSession, ServiceEventWaitor<ISuspendedDMEvent> eventWaitor = new ServiceEventWaitor<>(fSession, ISuspendedDMEvent.class);
ISuspendedDMEvent.class);
Query<Object> query = new Query<Object>() { Query<Object> query = new Query<Object>() {
@Override @Override

View file

@ -353,8 +353,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -463,8 +463,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -577,8 +577,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -696,8 +696,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts();
assertTrue("Expected a single thread but got " + threads.length, threads.length == 1); assertTrue("Expected a single thread but got " + threads.length, threads.length == 1);
final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -767,8 +767,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -777,8 +777,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts();
assertTrue("Expected two threads but got " + threads.length, threads.length == 2); assertTrue("Expected two threads but got " + threads.length, threads.length == 2);
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -819,8 +819,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -829,8 +829,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts();
assertTrue("Expected two threads but got " + threads.length, threads.length == 2); assertTrue("Expected two threads but got " + threads.length, threads.length == 2);
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -862,8 +862,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -876,8 +876,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts();
assertTrue("Expected two threads but got " + threads.length, threads.length == 2); assertTrue("Expected two threads but got " + threads.length, threads.length == 2);
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -910,8 +910,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -927,8 +927,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); final IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts();
assertTrue("Expected two threads but got " + threads.length, threads.length == 2); assertTrue("Expected two threads but got " + threads.length, threads.length == 2);
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -1000,8 +1000,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
}); });
assertFalse("expected no threads to be suspended, but found some", result); assertFalse("expected no threads to be suspended, but found some", result);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -1031,8 +1031,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1069,8 +1069,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1113,8 +1113,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1169,8 +1169,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1444,8 +1444,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1553,8 +1553,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1666,8 +1666,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -1996,8 +1996,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2109,8 +2109,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2227,8 +2227,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2345,8 +2345,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2471,8 +2471,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2585,8 +2585,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2703,8 +2703,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2824,8 +2824,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
public void testResumeProcessOneThreadStopped() throws Throwable { public void testResumeProcessOneThreadStopped() throws Throwable {
final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() }; final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() };
final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -2894,8 +2894,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2903,8 +2903,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() }; final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -2936,8 +2936,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2949,8 +2949,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() }; final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -2983,8 +2983,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -2999,8 +2999,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() }; final IExecutionDMContext[] processes = new IExecutionDMContext[] { SyncUtil.getContainerContext() };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -3082,8 +3082,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
}); });
assertFalse("expected no process to be suspended, but found some", result); assertFalse("expected no process to be suspended, but found some", result);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -3113,8 +3113,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3162,8 +3162,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3217,8 +3217,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3302,8 +3302,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0) }; SyncUtil.getExecutionContext(0) };
final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -3347,8 +3347,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
}); });
assertFalse("expected no contexts to be suspended, but found some", result); assertFalse("expected no contexts to be suspended, but found some", result);
final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running processes // No error should be thrown, the call should ignore running processes
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -3381,8 +3381,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3391,8 +3391,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0) }; SyncUtil.getExecutionContext(0) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -3427,8 +3427,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3441,8 +3441,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0) }; SyncUtil.getExecutionContext(0) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -3477,8 +3477,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3491,8 +3491,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(1) }; SyncUtil.getExecutionContext(1) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -3526,8 +3526,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3543,8 +3543,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0) }; SyncUtil.getExecutionContext(0) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -3650,8 +3650,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
}); });
assertFalse("expected no process to be suspended, but found some", result); assertFalse("expected no process to be suspended, but found some", result);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -3682,8 +3682,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3733,8 +3733,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3790,8 +3790,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3847,8 +3847,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3937,8 +3937,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3947,8 +3947,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) }; SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@Override @Override
@ -3983,8 +3983,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -3997,8 +3997,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) }; SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -4032,8 +4032,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -4049,8 +4049,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(), final IExecutionDMContext[] execDmcs = new IExecutionDMContext[] { SyncUtil.getContainerContext(),
SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) }; SyncUtil.getExecutionContext(0), SyncUtil.getExecutionContext(1) };
final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>( final ServiceEventWaitor<MIRunningEvent> eventWaitorRunning = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIRunningEvent.class); MIRunningEvent.class);
// No error should be thrown, the call should ignore running threads // No error should be thrown, the call should ignore running threads
runAsyncCall(new AsyncRunnable<Object>() { runAsyncCall(new AsyncRunnable<Object>() {
@ -4086,8 +4086,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -4137,8 +4137,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitorStopped = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitorStopped.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop
@ -4194,8 +4194,8 @@ public class GDBMultiNonStopRunControlTest extends BaseParametrizedTestCase {
// Run program until both threads are stopped // Run program until both threads are stopped
SyncUtil.addBreakpoint("firstBreakpoint", false); SyncUtil.addBreakpoint("firstBreakpoint", false);
final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( final ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRun.getSession(),
fMultiRun.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
SyncUtil.resumeAll(); SyncUtil.resumeAll();
eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); // Wait for first thread to stop

View file

@ -157,8 +157,8 @@ public class ThreadStackFrameSyncTest extends BaseParametrizedTestCase {
*/ */
@Test @Test
public void testChangingCurrentThreadCLINotification() throws Throwable { public void testChangingCurrentThreadCLINotification() throws Throwable {
ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRunControl.getSession(),
fMultiRunControl.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
// add a breakpoint in main // add a breakpoint in main
SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false);
@ -193,8 +193,8 @@ public class ThreadStackFrameSyncTest extends BaseParametrizedTestCase {
*/ */
@Test @Test
public void testChangingCurrentFrameCLINotification() throws Throwable { public void testChangingCurrentFrameCLINotification() throws Throwable {
ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRunControl.getSession(),
fMultiRunControl.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
// add a breakpoint in main // add a breakpoint in main
SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false);
@ -229,8 +229,8 @@ public class ThreadStackFrameSyncTest extends BaseParametrizedTestCase {
*/ */
@Test @Test
public void testGdbSyncServiceCanSwitchGDBThread() throws Throwable { public void testGdbSyncServiceCanSwitchGDBThread() throws Throwable {
ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRunControl.getSession(),
fMultiRunControl.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
// add a breakpoint in main // add a breakpoint in main
SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false);
@ -270,8 +270,8 @@ public class ThreadStackFrameSyncTest extends BaseParametrizedTestCase {
*/ */
@Test @Test
public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable { public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable {
ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>( ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<>(fMultiRunControl.getSession(),
fMultiRunControl.getSession(), MIStoppedEvent.class); MIStoppedEvent.class);
// add a breakpoint in main // add a breakpoint in main
SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false);

View file

@ -202,8 +202,7 @@ class DisassemblyColumnSupport implements IColumnSupport {
*/ */
@Override @Override
public void dispose() { public void dispose() {
for (Iterator<IContributedRulerColumn> iter = new ArrayList<>(fColumns).iterator(); iter for (Iterator<IContributedRulerColumn> iter = new ArrayList<>(fColumns).iterator(); iter.hasNext();)
.hasNext();)
removeColumn(getRuler(), iter.next()); removeColumn(getRuler(), iter.next());
fColumns.clear(); fColumns.clear();
} }

View file

@ -55,8 +55,7 @@ public class BreakpointVMNode extends AbstractBreakpointVMNode
@Override @Override
public void update(ILabelUpdate[] updates) { public void update(ILabelUpdate[] updates) {
Map<IElementLabelProvider, List<ILabelUpdate>> delegatesMap = new HashMap<>( Map<IElementLabelProvider, List<ILabelUpdate>> delegatesMap = new HashMap<>(1, 1);
1, 1);
for (final ILabelUpdate update : updates) { for (final ILabelUpdate update : updates) {
final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint();
@ -164,8 +163,7 @@ public class BreakpointVMNode extends AbstractBreakpointVMNode
@Override @Override
public void encodeElements(IElementMementoRequest[] updates) { public void encodeElements(IElementMementoRequest[] updates) {
Map<IElementMementoProvider, List<IElementMementoRequest>> delegatesMap = new HashMap<>( Map<IElementMementoProvider, List<IElementMementoRequest>> delegatesMap = new HashMap<>(1, 1);
1, 1);
for (final IElementMementoRequest update : updates) { for (final IElementMementoRequest update : updates) {
final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint();
@ -241,8 +239,7 @@ public class BreakpointVMNode extends AbstractBreakpointVMNode
@Override @Override
public void compareElements(IElementCompareRequest[] updates) { public void compareElements(IElementCompareRequest[] updates) {
Map<IElementMementoProvider, List<IElementCompareRequest>> delegatesMap = new HashMap<>( Map<IElementMementoProvider, List<IElementCompareRequest>> delegatesMap = new HashMap<>(1, 1);
1, 1);
for (final IElementCompareRequest update : updates) { for (final IElementCompareRequest update : updates) {
final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint(); final IBreakpoint bp = ((BreakpointVMContext) update.getElement()).getBreakpoint();

View file

@ -144,8 +144,7 @@ public class BreakpointVMProvider extends AbstractVMProvider {
} }
} }
List<BreakpointOrganizerVMContext> vmcs = new ArrayList<>( List<BreakpointOrganizerVMContext> vmcs = new ArrayList<>(bpsLists.size());
bpsLists.size());
for (Map.Entry<IAdaptable, List<IBreakpoint>> entry : bpsLists.entrySet()) { for (Map.Entry<IAdaptable, List<IBreakpoint>> entry : bpsLists.entrySet()) {
List<IBreakpoint> bpsList = entry.getValue(); List<IBreakpoint> bpsList = entry.getValue();
IBreakpoint[] bpsArray = bpsList.toArray(new IBreakpoint[bpsList.size()]); IBreakpoint[] bpsArray = bpsList.toArray(new IBreakpoint[bpsList.size()]);

View file

@ -424,10 +424,8 @@ public class FormattedValueRetriever {
final Map<IPropertiesUpdate, String[]> availableFormatsMap, final Map<IPropertiesUpdate, String[]> availableFormatsMap,
final Map<IPropertiesUpdate, String> elementFormatMap, final RequestMonitor rm) { final Map<IPropertiesUpdate, String> elementFormatMap, final RequestMonitor rm) {
final List<IPropertiesUpdate> outstandingUpdates = new ArrayList<>(updates.length); final List<IPropertiesUpdate> outstandingUpdates = new ArrayList<>(updates.length);
final Map<IPropertiesUpdate, List<String>> requestedFormatsMap = new HashMap<>( final Map<IPropertiesUpdate, List<String>> requestedFormatsMap = new HashMap<>(updates.length * 4 / 3);
updates.length * 4 / 3); final Map<IPropertiesUpdate, String> activeFormatsMap = new HashMap<>(updates.length * 4 / 3);
final Map<IPropertiesUpdate, String> activeFormatsMap = new HashMap<>(
updates.length * 4 / 3);
for (final IPropertiesUpdate update : updates) { for (final IPropertiesUpdate update : updates) {
String preferredFormat = FormattedValueVMUtil.getPreferredFormat(update.getPresentationContext()); String preferredFormat = FormattedValueVMUtil.getPreferredFormat(update.getPresentationContext());

View file

@ -203,8 +203,7 @@ public class BreakpointsMediator extends AbstractDsfService implements IBreakpoi
// We have to make a copy of the fPlatformBPs keys because uninstallBreakpoints() // We have to make a copy of the fPlatformBPs keys because uninstallBreakpoints()
// modifies the map as it walks through it. // modifies the map as it walks through it.
List<IBreakpointsTargetDMContext> platformBPKeysCopy = new ArrayList<>( List<IBreakpointsTargetDMContext> platformBPKeysCopy = new ArrayList<>(fPlatformBPs.size());
fPlatformBPs.size());
platformBPKeysCopy.addAll(0, fPlatformBPs.keySet()); platformBPKeysCopy.addAll(0, fPlatformBPs.keySet());
for (IBreakpointsTargetDMContext dmc : platformBPKeysCopy) { for (IBreakpointsTargetDMContext dmc : platformBPKeysCopy) {
stopTrackingBreakpoints(dmc, countingRm); stopTrackingBreakpoints(dmc, countingRm);
@ -567,8 +566,7 @@ public class BreakpointsMediator extends AbstractDsfService implements IBreakpoi
} }
// Get the list of corresponding back-end breakpoints // Get the list of corresponding back-end breakpoints
final List<IBreakpointDMContext> oldBpContexts = new ArrayList<>( final List<IBreakpointDMContext> oldBpContexts = new ArrayList<>(breakpointIDs.get(breakpoint));
breakpointIDs.get(breakpoint));
// Calculate the list of attributes maps that have not changed. // Calculate the list of attributes maps that have not changed.
// Immediately add these to the list of new breakpoint contexts, // Immediately add these to the list of new breakpoint contexts,

View file

@ -319,8 +319,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo
// We have to make a copy of the fPlatformBPs keys because uninstallBreakpoints() // We have to make a copy of the fPlatformBPs keys because uninstallBreakpoints()
// modifies the map as it walks through it. // modifies the map as it walks through it.
List<IBreakpointsTargetDMContext> platformBPKeysCopy = new ArrayList<>( List<IBreakpointsTargetDMContext> platformBPKeysCopy = new ArrayList<>(fPlatformBPs.size());
fPlatformBPs.size());
platformBPKeysCopy.addAll(0, fPlatformBPs.keySet()); platformBPKeysCopy.addAll(0, fPlatformBPs.keySet());
for (IBreakpointsTargetDMContext dmc : platformBPKeysCopy) { for (IBreakpointsTargetDMContext dmc : platformBPKeysCopy) {
stopTrackingBreakpoints(dmc, countingRm); stopTrackingBreakpoints(dmc, countingRm);
@ -527,8 +526,7 @@ public class BreakpointsMediator2 extends AbstractDsfService implements IBreakpo
targetBPsAttempted.add(new TargetBP(attrsList.get(i))); targetBPsAttempted.add(new TargetBP(attrsList.get(i)));
} }
final ArrayList<ITargetBreakpointInfo> targetBPsInstalled = new ArrayList<>( final ArrayList<ITargetBreakpointInfo> targetBPsInstalled = new ArrayList<>(attrsList.size());
attrsList.size());
// Update the breakpoint status when all back-end breakpoints have been installed // Update the breakpoint status when all back-end breakpoints have been installed
final CountingRequestMonitor installRM = new CountingRequestMonitor(getExecutor(), rm) { final CountingRequestMonitor installRM = new CountingRequestMonitor(getExecutor(), rm) {

View file

@ -287,8 +287,7 @@ public class CommandCache implements ICommandListener {
* them to point to the new super command. * them to point to the new super command.
*/ */
for (CommandInfo waitingEntry : new ArrayList<>( for (CommandInfo waitingEntry : new ArrayList<>(fPendingQWaitingForCoalescedCompletion)) {
fPendingQWaitingForCoalescedCompletion)) {
if (waitingEntry.getCoalescedCmd() == currentUnsentEntry) { if (waitingEntry.getCoalescedCmd() == currentUnsentEntry) {
/* /*
@ -469,8 +468,7 @@ public class CommandCache implements ICommandListener {
* we create a new result from the coalesced command for it. * we create a new result from the coalesced command for it.
*/ */
for (CommandInfo waitingEntry : new ArrayList<>( for (CommandInfo waitingEntry : new ArrayList<>(fPendingQWaitingForCoalescedCompletion)) {
fPendingQWaitingForCoalescedCompletion)) {
if (waitingEntry.getCoalescedCmd() == finalCachedCmd) { if (waitingEntry.getCoalescedCmd() == finalCachedCmd) {

View file

@ -485,29 +485,28 @@ public class DsfSession {
Dictionary<String, ?> serviceProperties = (Dictionary<String, ?>) _serviceProperties; Dictionary<String, ?> serviceProperties = (Dictionary<String, ?>) _serviceProperties;
// Build a list of listeners; // Build a list of listeners;
SortedMap<ListenerEntry, List<Method>> listeners = new TreeMap<>( SortedMap<ListenerEntry, List<Method>> listeners = new TreeMap<>(new Comparator<ListenerEntry>() {
new Comparator<ListenerEntry>() { @Override
@Override public int compare(ListenerEntry o1, ListenerEntry o2) {
public int compare(ListenerEntry o1, ListenerEntry o2) { if (o1.fListener == o2.fListener) {
if (o1.fListener == o2.fListener) { return 0;
return 0; }
} if (o1.fListener instanceof IDsfService && !(o2.fListener instanceof IDsfService)) {
if (o1.fListener instanceof IDsfService && !(o2.fListener instanceof IDsfService)) { return -1;
return -1; } else if (o2.fListener instanceof IDsfService && !(o1.fListener instanceof IDsfService)) {
} else if (o2.fListener instanceof IDsfService && !(o1.fListener instanceof IDsfService)) { return 1;
return 1; } else if ((o1.fListener instanceof IDsfService) && (o2.fListener instanceof IDsfService)) {
} else if ((o1.fListener instanceof IDsfService) && (o2.fListener instanceof IDsfService)) { return ((IDsfService) o1.fListener).getStartupNumber()
return ((IDsfService) o1.fListener).getStartupNumber() - ((IDsfService) o2.fListener).getStartupNumber();
- ((IDsfService) o2.fListener).getStartupNumber(); }
} return 1;
return 1; }
}
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return obj == this; return obj == this;
} }
}); });
// Build a list of listeners and methods that are registered for this event class. // Build a list of listeners and methods that are registered for this event class.
Class<?> eventClass = event.getClass(); Class<?> eventClass = event.getClass();

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -46,205 +47,190 @@ import org.eclipse.core.runtime.CoreException;
* invalidate their caches. * invalidate their caches.
* </p> * </p>
*/ */
public class ACPMSumDataGenerator public class ACPMSumDataGenerator implements IDataGenerator, IDataGenerator.Listener {
implements IDataGenerator, IDataGenerator.Listener
{
/** /**
* DSF executor used to serialize data access within this data generator. * DSF executor used to serialize data access within this data generator.
*/ */
final private DsfExecutor fExecutor; final private DsfExecutor fExecutor;
/** /**
* Data generators to retrieve original data to perform calculations on. * Data generators to retrieve original data to perform calculations on.
* The generators are accessed through the cache manager wrappers. * The generators are accessed through the cache manager wrappers.
*/ */
final private DataGeneratorCacheManager[] fDataGeneratorCMs; final private DataGeneratorCacheManager[] fDataGeneratorCMs;
/** /**
* List of listeners for this data generator. * List of listeners for this data generator.
*/ */
final private List<Listener> fListeners = new LinkedList<Listener>(); final private List<Listener> fListeners = new LinkedList<Listener>();
public ACPMSumDataGenerator(DsfExecutor executor, public ACPMSumDataGenerator(DsfExecutor executor, IDataGenerator[] generators) {
IDataGenerator[] generators) fExecutor = executor;
{
fExecutor = executor;
// Create wrappers for data generators and add ourselves as listener // Create wrappers for data generators and add ourselves as listener
// to their events. // to their events.
fDataGeneratorCMs = new DataGeneratorCacheManager[generators.length]; fDataGeneratorCMs = new DataGeneratorCacheManager[generators.length];
ImmediateInDsfExecutor immediateExecutor = ImmediateInDsfExecutor immediateExecutor = new ImmediateInDsfExecutor(fExecutor);
new ImmediateInDsfExecutor(fExecutor); for (int i = 0; i < generators.length; i++) {
for (int i = 0; i < generators.length; i++) { fDataGeneratorCMs[i] = new DataGeneratorCacheManager(immediateExecutor, generators[i]);
fDataGeneratorCMs[i] = new DataGeneratorCacheManager( generators[i].addListener(this);
immediateExecutor, generators[i]); }
generators[i].addListener(this); }
}
}
@Override @Override
public void getCount(final DataRequestMonitor<Integer> rm) { public void getCount(final DataRequestMonitor<Integer> rm) {
// Artificially delay the retrieval of the sum data to simulate // Artificially delay the retrieval of the sum data to simulate
// real processing time. // real processing time.
fExecutor.schedule( new Runnable() { fExecutor.schedule(new Runnable() {
@Override @Override
public void run() { public void run() {
// Create the transaction here to put all the ugly // Create the transaction here to put all the ugly
// code in one place. // code in one place.
new Transaction<Integer>() { new Transaction<Integer>() {
@Override @Override
protected Integer process() protected Integer process() throws Transaction.InvalidCacheException, CoreException {
throws Transaction.InvalidCacheException, return processCount(this);
CoreException }
{ }.request(rm);
return processCount(this); }
} }, PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}.request(rm); }
}
},
PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}
/** /**
* Perform the calculation to get the max count for the given transaction. * Perform the calculation to get the max count for the given transaction.
* @param transaction The ACPM transaction to use for calculation. * @param transaction The ACPM transaction to use for calculation.
* @return Calculated count. * @return Calculated count.
* @throws Transaction.InvalidCacheException {@link Transaction#process} * @throws Transaction.InvalidCacheException {@link Transaction#process}
* @throws CoreException See {@link Transaction#process} * @throws CoreException See {@link Transaction#process}
*/ */
private Integer processCount(Transaction<Integer> transaction) private Integer processCount(Transaction<Integer> transaction)
throws Transaction.InvalidCacheException, CoreException throws Transaction.InvalidCacheException, CoreException {
{ // Assemble all needed count caches into a collection.
// Assemble all needed count caches into a collection. List<ICache<Integer>> countCaches = new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length);
List<ICache<Integer>> countCaches = for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) {
new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length); countCaches.add(dataGeneratorCM.getCount());
for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) { }
countCaches.add(dataGeneratorCM.getCount()); // Validate all count caches at once. This executes needed requests
} // in parallel.
// Validate all count caches at once. This executes needed requests transaction.validate(countCaches);
// in parallel.
transaction.validate(countCaches);
// Calculate the max value and return. // Calculate the max value and return.
int maxCount = 0; int maxCount = 0;
for (ICache<Integer> countCache : countCaches) { for (ICache<Integer> countCache : countCaches) {
maxCount = Math.max(maxCount, countCache.getData()); maxCount = Math.max(maxCount, countCache.getData());
} }
return maxCount; return maxCount;
} }
@Override @Override
public void getValue(final int index, final DataRequestMonitor<Integer> rm) public void getValue(final int index, final DataRequestMonitor<Integer> rm) {
{ // Add a processing delay.
// Add a processing delay. fExecutor.schedule(new Runnable() {
fExecutor.schedule( new Runnable() { @Override
@Override public void run() {
public void run() { new Transaction<Integer>() {
new Transaction<Integer>() { @Override
@Override protected Integer process() throws Transaction.InvalidCacheException, CoreException {
protected Integer process() return processValue(this, index);
throws Transaction.InvalidCacheException, }
CoreException }.request(rm);
{ }
return processValue(this, index); }, PROCESSING_DELAY, TimeUnit.MILLISECONDS);
} }
}.request(rm);
}
},
PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}
/** /**
* Perform the calculation to get the sum of values at given index. * Perform the calculation to get the sum of values at given index.
* @param transaction The ACPM transaction to use for calculation. * @param transaction The ACPM transaction to use for calculation.
* @param index Index of value to calculate. * @param index Index of value to calculate.
* @return Calculated value. * @return Calculated value.
* @throws Transaction.InvalidCacheException {@link Transaction#process} * @throws Transaction.InvalidCacheException {@link Transaction#process}
* @throws CoreException See {@link Transaction#process} * @throws CoreException See {@link Transaction#process}
*/ */
private Integer processValue(Transaction<Integer> transaction, int index) private Integer processValue(Transaction<Integer> transaction, int index)
throws Transaction.InvalidCacheException, CoreException throws Transaction.InvalidCacheException, CoreException {
{ List<ICache<Integer>> valueCaches = new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length);
List<ICache<Integer>> valueCaches = for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) {
new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length); valueCaches.add(dataGeneratorCM.getValue(index));
for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) { }
valueCaches.add(dataGeneratorCM.getValue(index)); // Validate all value caches at once. This executes needed requests
} // in parallel.
// Validate all value caches at once. This executes needed requests transaction.validate(valueCaches);
// in parallel.
transaction.validate(valueCaches);
int sum = 0; int sum = 0;
for (ICache<Integer> valueCache : valueCaches) { for (ICache<Integer> valueCache : valueCaches) {
sum += valueCache.getData(); sum += valueCache.getData();
} }
return sum; return sum;
} }
@Override @Override
public void shutdown(final RequestMonitor rm) { public void shutdown(final RequestMonitor rm) {
for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) { for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) {
dataGeneratorCM.getDataGenerator().removeListener(this); dataGeneratorCM.getDataGenerator().removeListener(this);
dataGeneratorCM.dispose(); dataGeneratorCM.dispose();
rm.done(); rm.done();
} }
rm.done(); rm.done();
} }
@Override @Override
public void addListener(final Listener listener) { public void addListener(final Listener listener) {
// Must access fListeners on executor thread. // Must access fListeners on executor thread.
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fListeners.add(listener); fListeners.add(listener);
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
@Override @Override
public void removeListener(final Listener listener) { public void removeListener(final Listener listener) {
// Must access fListeners on executor thread. // Must access fListeners on executor thread.
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fListeners.remove(listener); fListeners.remove(listener);
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
@Override @Override
public void countChanged() { public void countChanged() {
// Must access fListeners on executor thread. // Must access fListeners on executor thread.
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
for (Listener listener : fListeners) { for (Listener listener : fListeners) {
listener.countChanged(); listener.countChanged();
} }
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
@Override @Override
public void valuesChanged(final Set<Integer> changed) { public void valuesChanged(final Set<Integer> changed) {
// Must access fListeners on executor thread. // Must access fListeners on executor thread.
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
for (Object listener : fListeners) { for (Object listener : fListeners) {
((Listener)listener).valuesChanged(changed); ((Listener) listener).valuesChanged(changed);
} }
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -62,431 +63,409 @@ import org.eclipse.swt.widgets.Table;
* </p> * </p>
*/ */
@ConfinedToDsfExecutor("fDisplayExecutor") @ConfinedToDsfExecutor("fDisplayExecutor")
public class ACPMSumDataViewer implements ILazyContentProvider public class ACPMSumDataViewer implements ILazyContentProvider {
{ /** View update frequency interval. */
/** View update frequency interval. */ final private static int UPDATE_INTERVAL = 10000;
final private static int UPDATE_INTERVAL = 10000;
/** Executor to use instead of Display.asyncExec(). **/ /** Executor to use instead of Display.asyncExec(). **/
@ThreadSafe @ThreadSafe
final private DsfExecutor fDisplayExecutor; final private DsfExecutor fDisplayExecutor;
/** Executor to use when retrieving data from data providers */ /** Executor to use when retrieving data from data providers */
@ThreadSafe @ThreadSafe
final private ImmediateInDsfExecutor fDataExecutor; final private ImmediateInDsfExecutor fDataExecutor;
// The viewer and generator that this content provider using. // The viewer and generator that this content provider using.
final private TableViewer fViewer; final private TableViewer fViewer;
final private DataGeneratorCacheManager[] fDataGeneratorCMs; final private DataGeneratorCacheManager[] fDataGeneratorCMs;
final private DataGeneratorCacheManager fSumGeneratorCM; final private DataGeneratorCacheManager fSumGeneratorCM;
// Fields used in request cancellation logic. // Fields used in request cancellation logic.
private List<ValueRequestMonitor> fItemDataRequestMonitors = private List<ValueRequestMonitor> fItemDataRequestMonitors = new LinkedList<ValueRequestMonitor>();
new LinkedList<ValueRequestMonitor>(); private Set<Integer> fIndexesToCancel = new HashSet<Integer>();
private Set<Integer> fIndexesToCancel = new HashSet<Integer>(); private int fCancelCallsPending = 0;
private int fCancelCallsPending = 0; private Future<?> fRefreshFuture;
private Future<?> fRefreshFuture;
public ACPMSumDataViewer(TableViewer viewer, public ACPMSumDataViewer(TableViewer viewer, ImmediateInDsfExecutor dataExecutor, IDataGenerator[] generators,
ImmediateInDsfExecutor dataExecutor, IDataGenerator[] generators, IDataGenerator sumGenerator) {
IDataGenerator sumGenerator) fViewer = viewer;
{ fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor(fViewer.getTable().getDisplay());
fViewer = viewer; fDataExecutor = dataExecutor;
fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor(
fViewer.getTable().getDisplay());
fDataExecutor = dataExecutor;
// Create wrappers for data generators. Don't need to register as // Create wrappers for data generators. Don't need to register as
// listeners to generator events because the cache managers ensure data // listeners to generator events because the cache managers ensure data
// are already registered for them. // are already registered for them.
fDataGeneratorCMs = new DataGeneratorCacheManager[generators.length]; fDataGeneratorCMs = new DataGeneratorCacheManager[generators.length];
for (int i = 0; i < generators.length; i++) { for (int i = 0; i < generators.length; i++) {
fDataGeneratorCMs[i] = fDataGeneratorCMs[i] = new DataGeneratorCacheManager(fDataExecutor, generators[i]);
new DataGeneratorCacheManager(fDataExecutor, generators[i]); }
} fSumGeneratorCM = new DataGeneratorCacheManager(fDataExecutor, sumGenerator);
fSumGeneratorCM =
new DataGeneratorCacheManager(fDataExecutor, sumGenerator);
// Schedule a task to refresh the viewer periodically. // Schedule a task to refresh the viewer periodically.
fRefreshFuture = fDisplayExecutor.scheduleAtFixedRate( fRefreshFuture = fDisplayExecutor.scheduleAtFixedRate(new Runnable() {
new Runnable() { @Override
@Override public void run() {
public void run() { queryItemCount();
queryItemCount(); }
} }, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}, }
UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
@Override @Override
public void dispose() { public void dispose() {
// Cancel the periodic task of refreshing the view. // Cancel the periodic task of refreshing the view.
fRefreshFuture.cancel(false); fRefreshFuture.cancel(false);
// Need to dispose cache managers that were created in this class. This // Need to dispose cache managers that were created in this class. This
// needs to be done on the cache manager's thread. // needs to be done on the cache manager's thread.
Query<Object> disposeCacheManagersQuery = new Query<Object>() { Query<Object> disposeCacheManagersQuery = new Query<Object>() {
@Override @Override
protected void execute(DataRequestMonitor<Object> rm) { protected void execute(DataRequestMonitor<Object> rm) {
fSumGeneratorCM.dispose(); fSumGeneratorCM.dispose();
for (DataGeneratorCacheManager dataGeneratorCM : for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) {
fDataGeneratorCMs) dataGeneratorCM.dispose();
{ }
dataGeneratorCM.dispose(); rm.setData(new Object());
} rm.done();
rm.setData(new Object()); }
rm.done(); };
} fDataExecutor.execute(disposeCacheManagersQuery);
}; try {
fDataExecutor.execute(disposeCacheManagersQuery); disposeCacheManagersQuery.get();
try { } catch (InterruptedException e) {
disposeCacheManagersQuery.get(); } catch (ExecutionException e) {
} }
catch (InterruptedException e) {}
catch (ExecutionException e) {}
// Cancel any outstanding data requests. // Cancel any outstanding data requests.
for (ValueRequestMonitor rm : fItemDataRequestMonitors) { for (ValueRequestMonitor rm : fItemDataRequestMonitors) {
rm.cancel(); rm.cancel();
} }
fItemDataRequestMonitors.clear(); fItemDataRequestMonitors.clear();
} }
@Override @Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// Set the initial count to the viewer after the input is set. // Set the initial count to the viewer after the input is set.
queryItemCount(); queryItemCount();
} }
@Override @Override
public void updateElement(final int index) { public void updateElement(final int index) {
// Calculate the visible index range. // Calculate the visible index range.
final int topIdx = fViewer.getTable().getTopIndex(); final int topIdx = fViewer.getTable().getTopIndex();
final int botIdx = topIdx + getVisibleItemCount(topIdx); final int botIdx = topIdx + getVisibleItemCount(topIdx);
// Request the item for the given index. // Request the item for the given index.
queryValue(index); queryValue(index);
// Invoke a cancel task with a delay. The delay allows multiple cancel // Invoke a cancel task with a delay. The delay allows multiple cancel
// calls to be combined together improving performance of the viewer. // calls to be combined together improving performance of the viewer.
fCancelCallsPending++; fCancelCallsPending++;
fDisplayExecutor.execute( fDisplayExecutor.execute(new Runnable() {
new Runnable() { @Override @Override
public void run() { public void run() {
cancelStaleRequests(topIdx, botIdx); cancelStaleRequests(topIdx, botIdx);
}}); }
} });
}
/** /**
* Calculates the number of visible items based on the top item index and * Calculates the number of visible items based on the top item index and
* table bounds. * table bounds.
* @param top Index of top item. * @param top Index of top item.
* @return calculated number of items in viewer * @return calculated number of items in viewer
*/ */
private int getVisibleItemCount(int top) { private int getVisibleItemCount(int top) {
Table table = fViewer.getTable(); Table table = fViewer.getTable();
int itemCount = table.getItemCount(); int itemCount = table.getItemCount();
return Math.min( return Math.min((table.getBounds().height / table.getItemHeight()) + 2, itemCount - top);
(table.getBounds().height / table.getItemHeight()) + 2, }
itemCount - top);
}
/** /**
* Retrieve the current count. When a new count is set to viewer, the viewer * Retrieve the current count. When a new count is set to viewer, the viewer
* will refresh all items as well. * will refresh all items as well.
*/ */
private void queryItemCount() { private void queryItemCount() {
// Create the request monitor to collect the count. This request // Create the request monitor to collect the count. This request
// monitor will be completed by the following transaction. // monitor will be completed by the following transaction.
final DataRequestMonitor<Integer> rm = final DataRequestMonitor<Integer> rm = new DataRequestMonitor<Integer>(fDisplayExecutor, null) {
new DataRequestMonitor<Integer>(fDisplayExecutor, null) @Override
{ protected void handleSuccess() {
@Override setCountToViewer(getData());
protected void handleSuccess() { }
setCountToViewer(getData());
}
@Override
protected void handleRejectedExecutionException() {} // Shutting down, ignore.
};
// Use a transaction, even with a single cache. This will ensure that @Override
// if the cache is reset during processing by an event. The request protected void handleRejectedExecutionException() {
// for data will be re-issued. } // Shutting down, ignore.
fDataExecutor.execute(new Runnable() { };
@Override
// Use a transaction, even with a single cache. This will ensure that
// if the cache is reset during processing by an event. The request
// for data will be re-issued.
fDataExecutor.execute(new Runnable() {
@Override
public void run() { public void run() {
new Transaction<Integer>() { new Transaction<Integer>() {
@Override @Override
protected Integer process() protected Integer process() throws Transaction.InvalidCacheException, CoreException {
throws Transaction.InvalidCacheException, CoreException return processCount(this);
{ }
return processCount(this); }.request(rm);
} }
}.request(rm); });
} }
});
}
/** /**
* Perform the count retrieval from the sum data generator. * Perform the count retrieval from the sum data generator.
* @param transaction The ACPM transaction to use for calculation. * @param transaction The ACPM transaction to use for calculation.
* @return Calculated count. * @return Calculated count.
* @throws Transaction.InvalidCacheException {@link Transaction#process} * @throws Transaction.InvalidCacheException {@link Transaction#process}
* @throws CoreException See {@link Transaction#process} * @throws CoreException See {@link Transaction#process}
*/ */
private Integer processCount(Transaction<Integer> transaction) private Integer processCount(Transaction<Integer> transaction)
throws Transaction.InvalidCacheException, CoreException throws Transaction.InvalidCacheException, CoreException {
{ ICache<Integer> countCache = fSumGeneratorCM.getCount();
ICache<Integer> countCache = fSumGeneratorCM.getCount(); transaction.validate(countCache);
transaction.validate(countCache); return countCache.getData();
return countCache.getData(); }
}
/** /**
* Set the givne count to the viewer. This will cause the viewer will * Set the givne count to the viewer. This will cause the viewer will
* refresh all items' data as well. * refresh all items' data as well.
* <p>Note: This method must be called in the display thread. </p> * <p>Note: This method must be called in the display thread. </p>
* @param count New count to set to viewer. * @param count New count to set to viewer.
*/ */
private void setCountToViewer(int count) { private void setCountToViewer(int count) {
if (!fViewer.getTable().isDisposed()) { if (!fViewer.getTable().isDisposed()) {
fViewer.setItemCount(count); fViewer.setItemCount(count);
fViewer.getTable().clearAll(); fViewer.getTable().clearAll();
} }
} }
/** /**
* Retrieve the current value for given index. * Retrieve the current value for given index.
*/ */
private void queryValue(final int index) { private void queryValue(final int index) {
// Create the request monitor to collect the value. This request // Create the request monitor to collect the value. This request
// monitor will be completed by the following transaction. // monitor will be completed by the following transaction.
final ValueRequestMonitor rm = new ValueRequestMonitor(index) { final ValueRequestMonitor rm = new ValueRequestMonitor(index) {
@Override @Override
protected void handleCompleted() { protected void handleCompleted() {
fItemDataRequestMonitors.remove(this); fItemDataRequestMonitors.remove(this);
if (isSuccess()) { if (isSuccess()) {
setValueToViewer(index, getData()); setValueToViewer(index, getData());
} }
} }
@Override
protected void handleRejectedExecutionException() {
// Shutting down, ignore.
}
};
// Save the value request monitor, to cancel it if the view is @Override
// scrolled. protected void handleRejectedExecutionException() {
fItemDataRequestMonitors.add(rm); // Shutting down, ignore.
}
};
// Use a transaction, even with a single cache. This will ensure that // Save the value request monitor, to cancel it if the view is
// if the cache is reset during processing by an event. The request // scrolled.
// for data will be re-issued. fItemDataRequestMonitors.add(rm);
fDataExecutor.execute(new Runnable() {
@Override // Use a transaction, even with a single cache. This will ensure that
// if the cache is reset during processing by an event. The request
// for data will be re-issued.
fDataExecutor.execute(new Runnable() {
@Override
public void run() { public void run() {
new Transaction<String>() { new Transaction<String>() {
@Override @Override
protected String process() protected String process() throws Transaction.InvalidCacheException, CoreException {
throws Transaction.InvalidCacheException, CoreException return processValue(this, index);
{ }
return processValue(this, index); }.request(rm);
} }
}.request(rm); });
} }
});
}
/** /**
* Write the view value to the viewer. * Write the view value to the viewer.
* <p>Note: This method must be called in the display thread. </p> * <p>Note: This method must be called in the display thread. </p>
* @param index Index of value to set. * @param index Index of value to set.
* @param value New value. * @param value New value.
*/ */
private void setValueToViewer(int index, String value) { private void setValueToViewer(int index, String value) {
if (!fViewer.getTable().isDisposed()) { if (!fViewer.getTable().isDisposed()) {
fViewer.replace(value, index); fViewer.replace(value, index);
} }
} }
/** /**
* Perform the calculation compose the string with data provider values * Perform the calculation compose the string with data provider values
* and the sum. This implementation also validates the result. * and the sum. This implementation also validates the result.
* @param transaction The ACPM transaction to use for calculation. * @param transaction The ACPM transaction to use for calculation.
* @param index Index of value to calculate. * @param index Index of value to calculate.
* @return Calculated value. * @return Calculated value.
* @throws Transaction.InvalidCacheException {@link Transaction#process} * @throws Transaction.InvalidCacheException {@link Transaction#process}
* @throws CoreException See {@link Transaction#process} * @throws CoreException See {@link Transaction#process}
*/ */
private String processValue(Transaction<String> transaction, int index) private String processValue(Transaction<String> transaction, int index)
throws Transaction.InvalidCacheException, CoreException throws Transaction.InvalidCacheException, CoreException {
{ List<ICache<Integer>> valueCaches = new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length);
List<ICache<Integer>> valueCaches = for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) {
new ArrayList<ICache<Integer>>(fDataGeneratorCMs.length); valueCaches.add(dataGeneratorCM.getValue(index));
for (DataGeneratorCacheManager dataGeneratorCM : fDataGeneratorCMs) { }
valueCaches.add(dataGeneratorCM.getValue(index)); // Validate all value caches at once. This executes needed requests
} // in parallel.
// Validate all value caches at once. This executes needed requests transaction.validate(valueCaches);
// in parallel.
transaction.validate(valueCaches);
// TODO: evaluate sum generator cache in parallel with value caches. // TODO: evaluate sum generator cache in parallel with value caches.
ICache<Integer> sumCache = fSumGeneratorCM.getValue(index); ICache<Integer> sumCache = fSumGeneratorCM.getValue(index);
transaction.validate(sumCache); transaction.validate(sumCache);
// Compose the string with values, sum, and validation result. // Compose the string with values, sum, and validation result.
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
int calcSum = 0; int calcSum = 0;
for (ICache<Integer> valueCache : valueCaches) { for (ICache<Integer> valueCache : valueCaches) {
if (result.length() != 0) result.append(" + "); if (result.length() != 0)
result.append(valueCache.getData()); result.append(" + ");
calcSum += valueCache.getData(); result.append(valueCache.getData());
} calcSum += valueCache.getData();
result.append(" = "); }
result.append(sumCache.getData()); result.append(" = ");
if (calcSum != sumCache.getData()) { result.append(sumCache.getData());
result.append(" !INCORRECT! "); if (calcSum != sumCache.getData()) {
} result.append(" !INCORRECT! ");
}
return result.toString(); return result.toString();
} }
/** /**
* Dedicated class for data item requests. This class holds the index * Dedicated class for data item requests. This class holds the index
* argument so it can be examined when canceling stale requests. * argument so it can be examined when canceling stale requests.
*/ */
private class ValueRequestMonitor extends DataRequestMonitor<String> { private class ValueRequestMonitor extends DataRequestMonitor<String> {
/** Index is used when canceling stale requests. */ /** Index is used when canceling stale requests. */
int fIndex; int fIndex;
ValueRequestMonitor(int index) { ValueRequestMonitor(int index) {
super(fDisplayExecutor, null); super(fDisplayExecutor, null);
fIndex = index; fIndex = index;
} }
@Override @Override
protected void handleRejectedExecutionException() { protected void handleRejectedExecutionException() {
// Shutting down, ignore. // Shutting down, ignore.
} }
} }
/** /**
* Cancels any outstanding value requests for items which are no longer * Cancels any outstanding value requests for items which are no longer
* visible in the viewer. * visible in the viewer.
* *
* @param topIdx Index of top visible item in viewer. * @param topIdx Index of top visible item in viewer.
* @param botIdx Index of bottom visible item in viewer. * @param botIdx Index of bottom visible item in viewer.
*/ */
private void cancelStaleRequests(int topIdx, int botIdx) { private void cancelStaleRequests(int topIdx, int botIdx) {
// Decrement the count of outstanding cancel calls. // Decrement the count of outstanding cancel calls.
fCancelCallsPending--; fCancelCallsPending--;
// Must check again, in case disposed while re-dispatching. // Must check again, in case disposed while re-dispatching.
if (fDataGeneratorCMs == null || fViewer.getTable().isDisposed()) { if (fDataGeneratorCMs == null || fViewer.getTable().isDisposed()) {
return; return;
} }
// Go through the outstanding requests and cancel any that // Go through the outstanding requests and cancel any that
// are not visible anymore. // are not visible anymore.
for (Iterator<ValueRequestMonitor> itr = for (Iterator<ValueRequestMonitor> itr = fItemDataRequestMonitors.iterator(); itr.hasNext();) {
fItemDataRequestMonitors.iterator(); itr.hasNext();) ValueRequestMonitor item = itr.next();
{ if (item.fIndex < topIdx || item.fIndex > botIdx) {
ValueRequestMonitor item = itr.next(); // Set the item to canceled status, so that the data provider
if (item.fIndex < topIdx || item.fIndex > botIdx) { // will ignore it.
// Set the item to canceled status, so that the data provider item.cancel();
// will ignore it.
item.cancel();
// Add the item index to list of indexes that were canceled, // Add the item index to list of indexes that were canceled,
// which will be sent to the table widget. // which will be sent to the table widget.
fIndexesToCancel.add(item.fIndex); fIndexesToCancel.add(item.fIndex);
// Remove the item from the outstanding cancel requests. // Remove the item from the outstanding cancel requests.
itr.remove(); itr.remove();
} }
} }
if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) { if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) {
Set<Integer> canceledIdxs = fIndexesToCancel; Set<Integer> canceledIdxs = fIndexesToCancel;
fIndexesToCancel = new HashSet<Integer>(); fIndexesToCancel = new HashSet<Integer>();
// Clear the indexes of the canceled request, so that the // Clear the indexes of the canceled request, so that the
// viewer knows to request them again when needed. // viewer knows to request them again when needed.
// Note: clearing using TableViewer.clear(int) seems very // Note: clearing using TableViewer.clear(int) seems very
// inefficient, it's better to use Table.clear(int[]). // inefficient, it's better to use Table.clear(int[]).
int[] canceledIdxsArray = new int[canceledIdxs.size()]; int[] canceledIdxsArray = new int[canceledIdxs.size()];
int i = 0; int i = 0;
for (Integer index : canceledIdxs) { for (Integer index : canceledIdxs) {
canceledIdxsArray[i++] = index; canceledIdxsArray[i++] = index;
} }
fViewer.getTable().clear(canceledIdxsArray); fViewer.getTable().clear(canceledIdxsArray);
} }
} }
/** /**
* The entry point for the example. * The entry point for the example.
* @param args Program arguments. * @param args Program arguments.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// Create the shell to hold the viewer. // Create the shell to hold the viewer.
Display display = new Display(); Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM); Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout()); shell.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH); GridData data = new GridData(GridData.FILL_BOTH);
shell.setLayoutData(data); shell.setLayoutData(data);
Font font = new Font(display, "Courier", 10, SWT.NORMAL); Font font = new Font(display, "Courier", 10, SWT.NORMAL);
// Create the table viewer. // Create the table viewer.
TableViewer tableViewer = TableViewer tableViewer = new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL);
new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL); tableViewer.getControl().setLayoutData(data);
tableViewer.getControl().setLayoutData(data);
DsfExecutor executor = new DefaultDsfExecutor("Example executor"); DsfExecutor executor = new DefaultDsfExecutor("Example executor");
// Create the data generator. // Create the data generator.
final IDataGenerator[] generators = new IDataGenerator[5]; final IDataGenerator[] generators = new IDataGenerator[5];
for (int i = 0; i < generators.length; i++) { for (int i = 0; i < generators.length; i++) {
generators[i] = new DataGeneratorWithExecutor(executor); generators[i] = new DataGeneratorWithExecutor(executor);
} }
final IDataGenerator sumGenerator = final IDataGenerator sumGenerator = new ACPMSumDataGenerator(executor, generators);
new ACPMSumDataGenerator(executor, generators);
// Create the content provider which will populate the viewer. // Create the content provider which will populate the viewer.
ACPMSumDataViewer contentProvider = new ACPMSumDataViewer( ACPMSumDataViewer contentProvider = new ACPMSumDataViewer(tableViewer, new ImmediateInDsfExecutor(executor),
tableViewer, new ImmediateInDsfExecutor(executor), generators, sumGenerator);
generators, sumGenerator); tableViewer.setContentProvider(contentProvider);
tableViewer.setContentProvider(contentProvider); tableViewer.setInput(new Object());
tableViewer.setInput(new Object());
// Open the shell and service the display dispatch loop until user // Open the shell and service the display dispatch loop until user
// closes the shell. // closes the shell.
shell.open(); shell.open();
while (!shell.isDisposed()) { while (!shell.isDisposed()) {
if (!display.readAndDispatch()) if (!display.readAndDispatch())
display.sleep(); display.sleep();
} }
// The IDataGenerator.shutdown() method is asynchronous, this requires // The IDataGenerator.shutdown() method is asynchronous, this requires
// using a query again in order to wait for its completion. // using a query again in order to wait for its completion.
Query<Object> shutdownQuery = new Query<Object>() { Query<Object> shutdownQuery = new Query<Object>() {
@Override @Override
protected void execute(DataRequestMonitor<Object> rm) { protected void execute(DataRequestMonitor<Object> rm) {
CountingRequestMonitor crm = new CountingRequestMonitor( CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm);
ImmediateExecutor.getInstance(), rm); for (int i = 0; i < generators.length; i++) {
for (int i = 0; i < generators.length; i++) { generators[i].shutdown(crm);
generators[i].shutdown(crm); }
} sumGenerator.shutdown(crm);
sumGenerator.shutdown(crm); crm.setDoneCount(generators.length);
crm.setDoneCount(generators.length); }
} };
};
executor.execute(shutdownQuery); executor.execute(shutdownQuery);
try { try {
shutdownQuery.get(); shutdownQuery.get();
} catch (Exception e) {} } catch (Exception e) {
}
// Shut down the display. // Shut down the display.
font.dispose(); font.dispose();
display.dispose(); display.dispose();
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -57,255 +58,245 @@ import org.eclipse.swt.widgets.Table;
* </p> * </p>
*/ */
@ConfinedToDsfExecutor("fDisplayExecutor") @ConfinedToDsfExecutor("fDisplayExecutor")
public class AsyncDataViewer public class AsyncDataViewer implements ILazyContentProvider, IDataGenerator.Listener {
implements ILazyContentProvider, IDataGenerator.Listener // Executor to use instead of Display.asyncExec().
{ @ThreadSafe
// Executor to use instead of Display.asyncExec(). final private DsfExecutor fDisplayExecutor;
@ThreadSafe
final private DsfExecutor fDisplayExecutor;
// The viewer and generator that this content provider using. // The viewer and generator that this content provider using.
final private TableViewer fViewer; final private TableViewer fViewer;
final private IDataGenerator fDataGenerator; final private IDataGenerator fDataGenerator;
// Fields used in request cancellation logic. // Fields used in request cancellation logic.
private List<ValueDataRequestMonitor> fItemDataRequestMonitors = private List<ValueDataRequestMonitor> fItemDataRequestMonitors = new LinkedList<ValueDataRequestMonitor>();
new LinkedList<ValueDataRequestMonitor>(); private Set<Integer> fIndexesToCancel = new HashSet<Integer>();
private Set<Integer> fIndexesToCancel = new HashSet<Integer>(); private int fCancelCallsPending = 0;
private int fCancelCallsPending = 0;
public AsyncDataViewer(TableViewer viewer, IDataGenerator generator) { public AsyncDataViewer(TableViewer viewer, IDataGenerator generator) {
fViewer = viewer; fViewer = viewer;
fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor( fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor(fViewer.getTable().getDisplay());
fViewer.getTable().getDisplay()); fDataGenerator = generator;
fDataGenerator = generator; fDataGenerator.addListener(this);
fDataGenerator.addListener(this); }
}
@Override @Override
public void dispose() { public void dispose() {
fDataGenerator.removeListener(this); fDataGenerator.removeListener(this);
} }
@Override @Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// Set the initial count to the viewer after the input is set. // Set the initial count to the viewer after the input is set.
queryItemCount(); queryItemCount();
} }
@Override @Override
public void updateElement(final int index) { public void updateElement(final int index) {
// Calculate the visible index range. // Calculate the visible index range.
final int topIdx = fViewer.getTable().getTopIndex(); final int topIdx = fViewer.getTable().getTopIndex();
final int botIdx = topIdx + getVisibleItemCount(topIdx); final int botIdx = topIdx + getVisibleItemCount(topIdx);
// Request the item for the given index. // Request the item for the given index.
queryValue(index); queryValue(index);
// Invoke a cancel task with a delay. The delay allows multiple cancel // Invoke a cancel task with a delay. The delay allows multiple cancel
// calls to be combined together improving performance of the viewer. // calls to be combined together improving performance of the viewer.
fCancelCallsPending++; fCancelCallsPending++;
fDisplayExecutor.schedule( fDisplayExecutor.schedule(new Runnable() {
new Runnable() { @Override @Override
public void run() { public void run() {
cancelStaleRequests(topIdx, botIdx); cancelStaleRequests(topIdx, botIdx);
}}, }
1, TimeUnit.MILLISECONDS); }, 1, TimeUnit.MILLISECONDS);
} }
/** /**
* Calculates the number of visible items based on the top item index and * Calculates the number of visible items based on the top item index and
* table bounds. * table bounds.
* @param top Index of top item. * @param top Index of top item.
* @return calculated number of items in viewer * @return calculated number of items in viewer
*/ */
private int getVisibleItemCount(int top) { private int getVisibleItemCount(int top) {
Table table = fViewer.getTable(); Table table = fViewer.getTable();
int itemCount = table.getItemCount(); int itemCount = table.getItemCount();
return Math.min( return Math.min((table.getBounds().height / table.getItemHeight()) + 2, itemCount - top);
(table.getBounds().height / table.getItemHeight()) + 2, }
itemCount - top);
}
@Override @Override
@ThreadSafe @ThreadSafe
public void countChanged() { public void countChanged() {
queryItemCount(); queryItemCount();
} }
@Override @Override
@ThreadSafe @ThreadSafe
public void valuesChanged(final Set<Integer> indexes) { public void valuesChanged(final Set<Integer> indexes) {
// Mark the changed items in table viewer as dirty, this will // Mark the changed items in table viewer as dirty, this will
// trigger update requests for these indexes if they are // trigger update requests for these indexes if they are
// visible in the viewer. // visible in the viewer.
final TableViewer tableViewer = fViewer; final TableViewer tableViewer = fViewer;
fDisplayExecutor.execute( new Runnable() { fDisplayExecutor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!fViewer.getTable().isDisposed()) { if (!fViewer.getTable().isDisposed()) {
for (Integer index : indexes) { for (Integer index : indexes) {
tableViewer.clear(index); tableViewer.clear(index);
} }
} }
}}); }
} });
}
/** /**
* Retrieve the up to date count. When a new count is set to viewer, the * Retrieve the up to date count. When a new count is set to viewer, the
* viewer will refresh all items as well. * viewer will refresh all items as well.
*/ */
private void queryItemCount() { private void queryItemCount() {
// Request count from data provider. When the count is returned, we // Request count from data provider. When the count is returned, we
// have to re-dispatch into the display thread to avoid calling // have to re-dispatch into the display thread to avoid calling
// the table widget on the DSF dispatch thread. // the table widget on the DSF dispatch thread.
fIndexesToCancel.clear(); fIndexesToCancel.clear();
fDataGenerator.getCount( fDataGenerator.getCount(
// Use the display executor to construct the request monitor, this // Use the display executor to construct the request monitor, this
// will cause the handleCompleted() method to be automatically // will cause the handleCompleted() method to be automatically
// called on the display thread. // called on the display thread.
new DataRequestMonitor<Integer>(fDisplayExecutor, null) { new DataRequestMonitor<Integer>(fDisplayExecutor, null) {
@Override @Override
protected void handleCompleted() { protected void handleCompleted() {
if (!fViewer.getTable().isDisposed()) { if (!fViewer.getTable().isDisposed()) {
fViewer.setItemCount(getData()); fViewer.setItemCount(getData());
fViewer.getTable().clearAll(); fViewer.getTable().clearAll();
} }
} }
}); });
} }
/**
* Retrieves value of an element at given index. When complete the value
* is written to the viewer.
* @param index Index of value to retrieve.
*/
private void queryValue(final int index) {
ValueDataRequestMonitor rm = new ValueDataRequestMonitor(index);
fItemDataRequestMonitors.add(rm);
fDataGenerator.getValue(index, rm);
}
/** /**
* Retrieves value of an element at given index. When complete the value * Dedicated class for data item requests. This class holds the index
* is written to the viewer. * argument so it can be examined when canceling stale requests.
* @param index Index of value to retrieve. */
*/ private class ValueDataRequestMonitor extends DataRequestMonitor<Integer> {
private void queryValue(final int index) {
ValueDataRequestMonitor rm = new ValueDataRequestMonitor(index);
fItemDataRequestMonitors.add(rm);
fDataGenerator.getValue(index, rm);
}
/** /** Index is used when canceling stale requests. */
* Dedicated class for data item requests. This class holds the index int fIndex;
* argument so it can be examined when canceling stale requests.
*/
private class ValueDataRequestMonitor extends DataRequestMonitor<Integer> {
/** Index is used when canceling stale requests. */ ValueDataRequestMonitor(int index) {
int fIndex; super(fDisplayExecutor, null);
fIndex = index;
}
ValueDataRequestMonitor(int index) { @Override
super(fDisplayExecutor, null); protected void handleCompleted() {
fIndex = index; fItemDataRequestMonitors.remove(this);
}
@Override // Check if the request completed successfully, otherwise ignore
protected void handleCompleted() { // it.
fItemDataRequestMonitors.remove(this); if (isSuccess()) {
if (!fViewer.getTable().isDisposed()) {
fViewer.replace(getData(), fIndex);
}
}
}
}
// Check if the request completed successfully, otherwise ignore private void cancelStaleRequests(int topIdx, int botIdx) {
// it. // Decrement the count of outstanding cancel calls.
if (isSuccess()) { fCancelCallsPending--;
if (!fViewer.getTable().isDisposed()) {
fViewer.replace(getData(), fIndex);
}
}
}
}
private void cancelStaleRequests(int topIdx, int botIdx) { // Must check again, in case disposed while re-dispatching.
// Decrement the count of outstanding cancel calls. if (fDataGenerator == null || fViewer.getTable().isDisposed())
fCancelCallsPending--; return;
// Must check again, in case disposed while re-dispatching. // Go through the outstanding requests and cancel any that
if (fDataGenerator == null || fViewer.getTable().isDisposed()) return; // are not visible anymore.
for (Iterator<ValueDataRequestMonitor> itr = fItemDataRequestMonitors.iterator(); itr.hasNext();) {
ValueDataRequestMonitor item = itr.next();
if (item.fIndex < topIdx || item.fIndex > botIdx) {
// Set the item to canceled status, so that the data provider
// will ignore it.
item.cancel();
// Go through the outstanding requests and cancel any that // Add the item index to list of indexes that were canceled,
// are not visible anymore. // which will be sent to the table widget.
for (Iterator<ValueDataRequestMonitor> itr = fIndexesToCancel.add(item.fIndex);
fItemDataRequestMonitors.iterator();
itr.hasNext();)
{
ValueDataRequestMonitor item = itr.next();
if (item.fIndex < topIdx || item.fIndex > botIdx) {
// Set the item to canceled status, so that the data provider
// will ignore it.
item.cancel();
// Add the item index to list of indexes that were canceled, // Remove the item from the outstanding cancel requests.
// which will be sent to the table widget. itr.remove();
fIndexesToCancel.add(item.fIndex); }
}
if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) {
Set<Integer> canceledIdxs = fIndexesToCancel;
fIndexesToCancel = new HashSet<Integer>();
// Remove the item from the outstanding cancel requests. // Clear the indexes of the canceled request, so that the
itr.remove(); // viewer knows to request them again when needed.
} // Note: clearing using TableViewer.clear(int) seems very
} // inefficient, it's better to use Table.clear(int[]).
if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) { int[] canceledIdxsArray = new int[canceledIdxs.size()];
Set<Integer> canceledIdxs = fIndexesToCancel; int i = 0;
fIndexesToCancel = new HashSet<Integer>(); for (Integer index : canceledIdxs) {
canceledIdxsArray[i++] = index;
}
fViewer.getTable().clear(canceledIdxsArray);
}
}
// Clear the indexes of the canceled request, so that the public static void main(String[] args) {
// viewer knows to request them again when needed. // Create the shell to hold the viewer.
// Note: clearing using TableViewer.clear(int) seems very Display display = new Display();
// inefficient, it's better to use Table.clear(int[]). Shell shell = new Shell(display, SWT.SHELL_TRIM);
int[] canceledIdxsArray = new int[canceledIdxs.size()]; shell.setLayout(new GridLayout());
int i = 0; GridData data = new GridData(GridData.FILL_BOTH);
for (Integer index : canceledIdxs) { shell.setLayoutData(data);
canceledIdxsArray[i++] = index; Font font = new Font(display, "Courier", 10, SWT.NORMAL);
}
fViewer.getTable().clear(canceledIdxsArray);
}
}
// Create the table viewer.
TableViewer tableViewer = new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL);
tableViewer.getControl().setLayoutData(data);
public static void main(String[] args) { // Create the data generator.
// Create the shell to hold the viewer. final IDataGenerator generator = new DataGeneratorWithExecutor();
Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH);
shell.setLayoutData(data);
Font font = new Font(display, "Courier", 10, SWT.NORMAL);
// Create the table viewer. // Create the content provider which will populate the viewer.
TableViewer tableViewer = AsyncDataViewer contentProvider = new AsyncDataViewer(tableViewer, generator);
new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL); tableViewer.setContentProvider(contentProvider);
tableViewer.getControl().setLayoutData(data); tableViewer.setInput(new Object());
// Create the data generator. // Open the shell and service the display dispatch loop until user
final IDataGenerator generator = new DataGeneratorWithExecutor(); // closes the shell.
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
// Create the content provider which will populate the viewer. // The IDataGenerator.shutdown() method is asynchronous, this requires
AsyncDataViewer contentProvider = // using a query again in order to wait for its completion.
new AsyncDataViewer(tableViewer, generator); Query<Object> shutdownQuery = new Query<Object>() {
tableViewer.setContentProvider(contentProvider); @Override
tableViewer.setInput(new Object()); protected void execute(DataRequestMonitor<Object> rm) {
generator.shutdown(rm);
}
};
ImmediateExecutor.getInstance().execute(shutdownQuery);
try {
shutdownQuery.get();
} catch (Exception e) {
}
// Open the shell and service the display dispatch loop until user // Shut down the display.
// closes the shell. font.dispose();
shell.open(); display.dispose();
while (!shell.isDisposed()) { }
if (!display.readAndDispatch())
display.sleep();
}
// The IDataGenerator.shutdown() method is asynchronous, this requires
// using a query again in order to wait for its completion.
Query<Object> shutdownQuery = new Query<Object>() {
@Override
protected void execute(DataRequestMonitor<Object> rm) {
generator.shutdown(rm);
}
};
ImmediateExecutor.getInstance().execute(shutdownQuery);
try {
shutdownQuery.get();
} catch (Exception e) {}
// Shut down the display.
font.dispose();
display.dispose();
}
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -38,144 +39,128 @@ import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
*/ */
public class AsyncSumDataGenerator implements IDataGenerator { public class AsyncSumDataGenerator implements IDataGenerator {
/** /**
* DSF executor used to serialize data access within this data generator. * DSF executor used to serialize data access within this data generator.
*/ */
final private DsfExecutor fExecutor; final private DsfExecutor fExecutor;
/** /**
* Data generators to retrieve original data to perform calculations on. * Data generators to retrieve original data to perform calculations on.
*/ */
final private IDataGenerator[] fDataGenerators; final private IDataGenerator[] fDataGenerators;
public AsyncSumDataGenerator(DsfExecutor executor, public AsyncSumDataGenerator(DsfExecutor executor, IDataGenerator[] generators) {
IDataGenerator[] generators) fExecutor = executor;
{ fDataGenerators = generators;
fExecutor = executor; }
fDataGenerators = generators;
}
@Override @Override
public void getCount(final DataRequestMonitor<Integer> rm) { public void getCount(final DataRequestMonitor<Integer> rm) {
// Artificially delay the retrieval of the sum data to simulate // Artificially delay the retrieval of the sum data to simulate
// real processing time. // real processing time.
fExecutor.schedule( new Runnable() { fExecutor.schedule(new Runnable() {
@Override @Override
public void run() { public void run() {
doGetCount(rm); doGetCount(rm);
} }
}, }, PROCESSING_DELAY, TimeUnit.MILLISECONDS);
PROCESSING_DELAY, TimeUnit.MILLISECONDS); }
}
/** /**
* Performs the actual count retrieval and calculation. * Performs the actual count retrieval and calculation.
* @param rm Request monitor to complete with data. * @param rm Request monitor to complete with data.
*/ */
private void doGetCount(final DataRequestMonitor<Integer> rm) { private void doGetCount(final DataRequestMonitor<Integer> rm) {
// Array to store counts retrieved asynchronously // Array to store counts retrieved asynchronously
final int[] counts = new int[fDataGenerators.length]; final int[] counts = new int[fDataGenerators.length];
// Counting request monitor is called once all data is retrieved. // Counting request monitor is called once all data is retrieved.
final CountingRequestMonitor crm = final CountingRequestMonitor crm = new CountingRequestMonitor(fExecutor, rm) {
new CountingRequestMonitor(fExecutor, rm) @Override
{ protected void handleSuccess() {
@Override // Pick the highest count value.
protected void handleSuccess() { Arrays.sort(counts, 0, counts.length - 1);
// Pick the highest count value. int maxCount = counts[counts.length - 1];
Arrays.sort(counts, 0, counts.length - 1); rm.setData(maxCount);
int maxCount = counts[counts.length - 1]; rm.done();
rm.setData(maxCount); };
rm.done(); };
};
};
// Each call to data generator fills in one value in array. // Each call to data generator fills in one value in array.
for (int i = 0; i < fDataGenerators.length; i++) { for (int i = 0; i < fDataGenerators.length; i++) {
final int finalI = i; final int finalI = i;
fDataGenerators[i].getCount( fDataGenerators[i].getCount(new DataRequestMonitor<Integer>(ImmediateExecutor.getInstance(), crm) {
new DataRequestMonitor<Integer>( @Override
ImmediateExecutor.getInstance(), crm) protected void handleSuccess() {
{ counts[finalI] = getData();
@Override crm.done();
protected void handleSuccess() { }
counts[finalI] = getData(); });
crm.done(); }
} crm.setDoneCount(fDataGenerators.length);
}); }
}
crm.setDoneCount(fDataGenerators.length);
}
@Override @Override
public void getValue(final int index, final DataRequestMonitor<Integer> rm) public void getValue(final int index, final DataRequestMonitor<Integer> rm) {
{ // Artificially delay the retrieval of the sum data to simulate
// Artificially delay the retrieval of the sum data to simulate // real processing time.
// real processing time. fExecutor.schedule(new Runnable() {
fExecutor.schedule( new Runnable() { @Override
@Override public void run() {
public void run() { doGetValue(index, rm);
doGetValue(index, rm); }
} }, PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}, }
PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}
/** /**
* Performs the actual value retrieval and calculation. * Performs the actual value retrieval and calculation.
* @param rm Request monitor to complete with data. * @param rm Request monitor to complete with data.
*/ */
private void doGetValue(int index, final DataRequestMonitor<Integer> rm) { private void doGetValue(int index, final DataRequestMonitor<Integer> rm) {
// Array to store counts retrieved asynchronously // Array to store counts retrieved asynchronously
final int[] values = new int[fDataGenerators.length]; final int[] values = new int[fDataGenerators.length];
// Counting request monitor is called once all data is retrieved. // Counting request monitor is called once all data is retrieved.
final CountingRequestMonitor crm = final CountingRequestMonitor crm = new CountingRequestMonitor(fExecutor, rm) {
new CountingRequestMonitor(fExecutor, rm) @Override
{ protected void handleSuccess() {
@Override // Sum up values in array.
protected void handleSuccess() { int sum = 0;
// Sum up values in array. for (int value : values) {
int sum = 0; sum += value;
for (int value : values) { }
sum += value; rm.setData(sum);
} rm.done();
rm.setData(sum); };
rm.done(); };
};
};
// Each call to data generator fills in one value in array. // Each call to data generator fills in one value in array.
for (int i = 0; i < fDataGenerators.length; i++) { for (int i = 0; i < fDataGenerators.length; i++) {
final int finalI = i; final int finalI = i;
fDataGenerators[i].getValue( fDataGenerators[i].getValue(index, new DataRequestMonitor<Integer>(ImmediateExecutor.getInstance(), crm) {
index, @Override
new DataRequestMonitor<Integer>( protected void handleSuccess() {
ImmediateExecutor.getInstance(), crm) values[finalI] = getData();
{ crm.done();
@Override }
protected void handleSuccess() { });
values[finalI] = getData(); }
crm.done(); crm.setDoneCount(fDataGenerators.length);
} }
});
}
crm.setDoneCount(fDataGenerators.length);
}
@Override @Override
public void shutdown(RequestMonitor rm) { public void shutdown(RequestMonitor rm) {
rm.done(); rm.done();
} }
@Override @Override
public void addListener(final Listener listener) { public void addListener(final Listener listener) {
// no events generated // no events generated
} }
@Override @Override
public void removeListener(Listener listener) { public void removeListener(Listener listener) {
// no events generated // no events generated
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -65,354 +66,334 @@ import org.eclipse.swt.widgets.Table;
* </p> * </p>
*/ */
@ConfinedToDsfExecutor("fDisplayExecutor") @ConfinedToDsfExecutor("fDisplayExecutor")
public class AsyncSumDataViewer implements ILazyContentProvider public class AsyncSumDataViewer implements ILazyContentProvider {
{ /** View update frequency interval. */
/** View update frequency interval. */ final private static int UPDATE_INTERVAL = 10000;
final private static int UPDATE_INTERVAL = 10000;
/** Executor to use instead of Display.asyncExec(). **/ /** Executor to use instead of Display.asyncExec(). **/
@ThreadSafe @ThreadSafe
final private DsfExecutor fDisplayExecutor; final private DsfExecutor fDisplayExecutor;
// The viewer and generator that this content provider using. // The viewer and generator that this content provider using.
final private TableViewer fViewer; final private TableViewer fViewer;
final private IDataGenerator[] fDataGenerators; final private IDataGenerator[] fDataGenerators;
final private IDataGenerator fSumGenerator; final private IDataGenerator fSumGenerator;
// Fields used in request cancellation logic. // Fields used in request cancellation logic.
private List<ValueCountingRequestMonitor> fItemDataRequestMonitors = private List<ValueCountingRequestMonitor> fItemDataRequestMonitors = new LinkedList<ValueCountingRequestMonitor>();
new LinkedList<ValueCountingRequestMonitor>(); private Set<Integer> fIndexesToCancel = new HashSet<Integer>();
private Set<Integer> fIndexesToCancel = new HashSet<Integer>(); private int fCancelCallsPending = 0;
private int fCancelCallsPending = 0; private Future<?> fRefreshFuture;
private Future<?> fRefreshFuture;
public AsyncSumDataViewer(TableViewer viewer, public AsyncSumDataViewer(TableViewer viewer, IDataGenerator[] generators, IDataGenerator sumGenerator) {
IDataGenerator[] generators, IDataGenerator sumGenerator) fViewer = viewer;
{ fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor(fViewer.getTable().getDisplay());
fViewer = viewer; fDataGenerators = generators;
fDisplayExecutor = DisplayDsfExecutor.getDisplayDsfExecutor( fSumGenerator = sumGenerator;
fViewer.getTable().getDisplay());
fDataGenerators = generators;
fSumGenerator = sumGenerator;
// Schedule a task to refresh the viewer periodically. // Schedule a task to refresh the viewer periodically.
fRefreshFuture = fDisplayExecutor.scheduleAtFixedRate( fRefreshFuture = fDisplayExecutor.scheduleAtFixedRate(new Runnable() {
new Runnable() { @Override
@Override
public void run() {
queryItemCount();
}
},
UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
@Override
public void dispose() {
// Cancel the periodic task of refreshing the view.
fRefreshFuture.cancel(false);
// Cancel any outstanding data requests.
for (ValueCountingRequestMonitor rm : fItemDataRequestMonitors) {
rm.cancel();
}
fItemDataRequestMonitors.clear();
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// Set the initial count to the viewer after the input is set.
queryItemCount();
}
@Override
public void updateElement(final int index) {
// Calculate the visible index range.
final int topIdx = fViewer.getTable().getTopIndex();
final int botIdx = topIdx + getVisibleItemCount(topIdx);
// Request the item for the given index.
queryValue(index);
// Invoke a cancel task with a delay. The delay allows multiple cancel
// calls to be combined together improving performance of the viewer.
fCancelCallsPending++;
fDisplayExecutor.execute(
new Runnable() { @Override
public void run() { public void run() {
cancelStaleRequests(topIdx, botIdx); queryItemCount();
}}); }
} }, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
/** @Override
* Calculates the number of visible items based on the top item index and public void dispose() {
* table bounds. // Cancel the periodic task of refreshing the view.
* @param top Index of top item. fRefreshFuture.cancel(false);
* @return calculated number of items in viewer
*/
private int getVisibleItemCount(int top) {
Table table = fViewer.getTable();
int itemCount = table.getItemCount();
return Math.min(
(table.getBounds().height / table.getItemHeight()) + 2,
itemCount - top);
}
/** // Cancel any outstanding data requests.
* Retrieve the up to date count. for (ValueCountingRequestMonitor rm : fItemDataRequestMonitors) {
*/ rm.cancel();
private void queryItemCount() { }
// Note:The count is retrieved from the sum generator only, the sum fItemDataRequestMonitors.clear();
// generator is responsible for calculating the count based on }
// individual data providers' counts.
fIndexesToCancel.clear();
fSumGenerator.getCount(
new DataRequestMonitor<Integer>(fDisplayExecutor, null) {
@Override
protected void handleSuccess() {
setCountToViewer(getData());
}
@Override
protected void handleRejectedExecutionException() {
// Shutting down, ignore.
}
});
}
/** @Override
* Set the givne count to the viewer. This will cause the viewer will public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
* refresh all items' data as well. // Set the initial count to the viewer after the input is set.
* @param count New count to set to viewer. queryItemCount();
*/ }
private void setCountToViewer(int count) {
if (!fViewer.getTable().isDisposed()) {
fViewer.setItemCount(count);
fViewer.getTable().clearAll();
}
}
/** @Override
* Retrieves value of an element at given index. When complete the value public void updateElement(final int index) {
* is written to the viewer. // Calculate the visible index range.
* @param index Index of value to retrieve. final int topIdx = fViewer.getTable().getTopIndex();
*/ final int botIdx = topIdx + getVisibleItemCount(topIdx);
private void queryValue(final int index) {
// Values retrieved asynchronously from providers are stored in local
// arrays.
final int[] values = new int[fDataGenerators.length];
final int[] sum = new int[1];
// Counting request monitor is invoked when the required number of // Request the item for the given index.
// value requests is completed. queryValue(index);
final ValueCountingRequestMonitor crm =
new ValueCountingRequestMonitor(index)
{
@Override
protected void handleCompleted() {
fItemDataRequestMonitors.remove(this);
// Check if the request completed successfully, otherwise // Invoke a cancel task with a delay. The delay allows multiple cancel
// ignore it. // calls to be combined together improving performance of the viewer.
if (isSuccess()) { fCancelCallsPending++;
StringBuilder result = new StringBuilder(); fDisplayExecutor.execute(new Runnable() {
int calcSum = 0; @Override
for (int value : values) { public void run() {
if (result.length() != 0) result.append(" + "); cancelStaleRequests(topIdx, botIdx);
result.append(value); }
calcSum += value; });
} }
result.append(" = ");
result.append(sum[0]);
if (calcSum != sum[0]) {
result.append(" !INCORRECT! ");
}
setValueToViewer(fIndex, result.toString());
}
};
};
// Request data from each data generator. /**
for (int i = 0; i < fDataGenerators.length; i++) { * Calculates the number of visible items based on the top item index and
final int finalI = i; * table bounds.
fDataGenerators[i].getValue( * @param top Index of top item.
index, * @return calculated number of items in viewer
// Use the display executor to construct the request monitor, */
// this will cause the handleCompleted() method to be private int getVisibleItemCount(int top) {
// automatically called on the display thread. Table table = fViewer.getTable();
new DataRequestMonitor<Integer>( int itemCount = table.getItemCount();
ImmediateExecutor.getInstance(), crm) return Math.min((table.getBounds().height / table.getItemHeight()) + 2, itemCount - top);
{ }
@Override
protected void handleSuccess() {
values[finalI] = getData();
crm.done();
}
});
}
// Separately request data from the sum data generator. /**
fSumGenerator.getValue( * Retrieve the up to date count.
index, */
new DataRequestMonitor<Integer>( private void queryItemCount() {
ImmediateExecutor.getInstance(), crm) // Note:The count is retrieved from the sum generator only, the sum
{ // generator is responsible for calculating the count based on
@Override // individual data providers' counts.
protected void handleSuccess() { fIndexesToCancel.clear();
sum[0] = getData(); fSumGenerator.getCount(new DataRequestMonitor<Integer>(fDisplayExecutor, null) {
crm.done(); @Override
} protected void handleSuccess() {
}); setCountToViewer(getData());
}
crm.setDoneCount(fDataGenerators.length + 1); @Override
fItemDataRequestMonitors.add(crm); protected void handleRejectedExecutionException() {
} // Shutting down, ignore.
}
});
}
/** /**
* Write the view value to the viewer. * Set the givne count to the viewer. This will cause the viewer will
* <p>Note: This method must be called in the display thread. </p> * refresh all items' data as well.
* @param index Index of value to set. * @param count New count to set to viewer.
* @param value New value. */
*/ private void setCountToViewer(int count) {
private void setValueToViewer(int index, String value) { if (!fViewer.getTable().isDisposed()) {
if (!fViewer.getTable().isDisposed()) { fViewer.setItemCount(count);
fViewer.replace(value, index); fViewer.getTable().clearAll();
} }
} }
/** /**
* Dedicated class for data item requests. This class holds the index * Retrieves value of an element at given index. When complete the value
* argument so it can be examined when canceling stale requests. * is written to the viewer.
*/ * @param index Index of value to retrieve.
private class ValueCountingRequestMonitor extends CountingRequestMonitor { */
/** Index is used when canceling stale requests. */ private void queryValue(final int index) {
int fIndex; // Values retrieved asynchronously from providers are stored in local
// arrays.
final int[] values = new int[fDataGenerators.length];
final int[] sum = new int[1];
ValueCountingRequestMonitor(int index) { // Counting request monitor is invoked when the required number of
super(fDisplayExecutor, null); // value requests is completed.
fIndex = index; final ValueCountingRequestMonitor crm = new ValueCountingRequestMonitor(index) {
} @Override
protected void handleCompleted() {
fItemDataRequestMonitors.remove(this);
@Override // Check if the request completed successfully, otherwise
protected void handleRejectedExecutionException() { // ignore it.
// Shutting down, ignore. if (isSuccess()) {
} StringBuilder result = new StringBuilder();
} int calcSum = 0;
for (int value : values) {
if (result.length() != 0)
result.append(" + ");
result.append(value);
calcSum += value;
}
result.append(" = ");
result.append(sum[0]);
if (calcSum != sum[0]) {
result.append(" !INCORRECT! ");
}
setValueToViewer(fIndex, result.toString());
}
};
};
/** // Request data from each data generator.
* Cancels any outstanding value requests for items which are no longer for (int i = 0; i < fDataGenerators.length; i++) {
* visible in the viewer. final int finalI = i;
* fDataGenerators[i].getValue(index,
* @param topIdx Index of top visible item in viewer. // Use the display executor to construct the request monitor,
* @param botIdx Index of bottom visible item in viewer. // this will cause the handleCompleted() method to be
*/ // automatically called on the display thread.
private void cancelStaleRequests(int topIdx, int botIdx) { new DataRequestMonitor<Integer>(ImmediateExecutor.getInstance(), crm) {
// Decrement the count of outstanding cancel calls. @Override
fCancelCallsPending--; protected void handleSuccess() {
values[finalI] = getData();
crm.done();
}
});
}
// Must check again, in case disposed while re-dispatching. // Separately request data from the sum data generator.
if (fDataGenerators == null || fViewer.getTable().isDisposed()) return; fSumGenerator.getValue(index, new DataRequestMonitor<Integer>(ImmediateExecutor.getInstance(), crm) {
@Override
protected void handleSuccess() {
sum[0] = getData();
crm.done();
}
});
// Go through the outstanding requests and cancel any that crm.setDoneCount(fDataGenerators.length + 1);
// are not visible anymore. fItemDataRequestMonitors.add(crm);
for (Iterator<ValueCountingRequestMonitor> itr = }
fItemDataRequestMonitors.iterator(); itr.hasNext();)
{
ValueCountingRequestMonitor item = itr.next();
if (item.fIndex < topIdx || item.fIndex > botIdx) {
// Set the item to canceled status, so that the data provider
// will ignore it.
item.cancel();
// Add the item index to list of indexes that were canceled, /**
// which will be sent to the table widget. * Write the view value to the viewer.
fIndexesToCancel.add(item.fIndex); * <p>Note: This method must be called in the display thread. </p>
* @param index Index of value to set.
* @param value New value.
*/
private void setValueToViewer(int index, String value) {
if (!fViewer.getTable().isDisposed()) {
fViewer.replace(value, index);
}
}
// Remove the item from the outstanding cancel requests. /**
itr.remove(); * Dedicated class for data item requests. This class holds the index
} * argument so it can be examined when canceling stale requests.
} */
if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) { private class ValueCountingRequestMonitor extends CountingRequestMonitor {
Set<Integer> canceledIdxs = fIndexesToCancel; /** Index is used when canceling stale requests. */
fIndexesToCancel = new HashSet<Integer>(); int fIndex;
// Clear the indexes of the canceled request, so that the ValueCountingRequestMonitor(int index) {
// viewer knows to request them again when needed. super(fDisplayExecutor, null);
// Note: clearing using TableViewer.clear(int) seems very fIndex = index;
// inefficient, it's better to use Table.clear(int[]). }
int[] canceledIdxsArray = new int[canceledIdxs.size()];
int i = 0;
for (Integer index : canceledIdxs) {
canceledIdxsArray[i++] = index;
}
fViewer.getTable().clear(canceledIdxsArray);
}
}
/** @Override
* The entry point for the example. protected void handleRejectedExecutionException() {
* @param args Program arguments. // Shutting down, ignore.
*/ }
public static void main(String[] args) { }
// Create the shell to hold the viewer.
Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH);
shell.setLayoutData(data);
Font font = new Font(display, "Courier", 10, SWT.NORMAL);
// Create the table viewer. /**
TableViewer tableViewer = * Cancels any outstanding value requests for items which are no longer
new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL); * visible in the viewer.
tableViewer.getControl().setLayoutData(data); *
* @param topIdx Index of top visible item in viewer.
* @param botIdx Index of bottom visible item in viewer.
*/
private void cancelStaleRequests(int topIdx, int botIdx) {
// Decrement the count of outstanding cancel calls.
fCancelCallsPending--;
// Single executor (and single thread) is used by all data generators, // Must check again, in case disposed while re-dispatching.
// including the sum generator. if (fDataGenerators == null || fViewer.getTable().isDisposed())
DsfExecutor executor = new DefaultDsfExecutor("Example executor"); return;
// Create the data generator. // Go through the outstanding requests and cancel any that
final IDataGenerator[] generators = new IDataGenerator[5]; // are not visible anymore.
for (int i = 0; i < generators.length; i++) { for (Iterator<ValueCountingRequestMonitor> itr = fItemDataRequestMonitors.iterator(); itr.hasNext();) {
generators[i] = new DataGeneratorWithExecutor(executor); ValueCountingRequestMonitor item = itr.next();
} if (item.fIndex < topIdx || item.fIndex > botIdx) {
final IDataGenerator sumGenerator = // Set the item to canceled status, so that the data provider
new AsyncSumDataGenerator(executor, generators); // will ignore it.
item.cancel();
// Create the content provider which will populate the viewer. // Add the item index to list of indexes that were canceled,
AsyncSumDataViewer contentProvider = // which will be sent to the table widget.
new AsyncSumDataViewer(tableViewer, generators, sumGenerator); fIndexesToCancel.add(item.fIndex);
tableViewer.setContentProvider(contentProvider);
tableViewer.setInput(new Object());
// Open the shell and service the display dispatch loop until user // Remove the item from the outstanding cancel requests.
// closes the shell. itr.remove();
shell.open(); }
while (!shell.isDisposed()) { }
if (!display.readAndDispatch()) if (!fIndexesToCancel.isEmpty() && fCancelCallsPending == 0) {
display.sleep(); Set<Integer> canceledIdxs = fIndexesToCancel;
} fIndexesToCancel = new HashSet<Integer>();
// The IDataGenerator.shutdown() method is asynchronous, this requires // Clear the indexes of the canceled request, so that the
// using a query again in order to wait for its completion. // viewer knows to request them again when needed.
Query<Object> shutdownQuery = new Query<Object>() { // Note: clearing using TableViewer.clear(int) seems very
@Override // inefficient, it's better to use Table.clear(int[]).
protected void execute(DataRequestMonitor<Object> rm) { int[] canceledIdxsArray = new int[canceledIdxs.size()];
CountingRequestMonitor crm = new CountingRequestMonitor( int i = 0;
ImmediateExecutor.getInstance(), rm); for (Integer index : canceledIdxs) {
for (int i = 0; i < generators.length; i++) { canceledIdxsArray[i++] = index;
generators[i].shutdown(crm); }
} fViewer.getTable().clear(canceledIdxsArray);
sumGenerator.shutdown(crm); }
crm.setDoneCount(generators.length); }
}
};
executor.execute(shutdownQuery); /**
try { * The entry point for the example.
shutdownQuery.get(); * @param args Program arguments.
} catch (Exception e) {} */
public static void main(String[] args) {
// Create the shell to hold the viewer.
Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH);
shell.setLayoutData(data);
Font font = new Font(display, "Courier", 10, SWT.NORMAL);
// Shut down the display. // Create the table viewer.
font.dispose(); TableViewer tableViewer = new TableViewer(shell, SWT.BORDER | SWT.VIRTUAL);
display.dispose(); tableViewer.getControl().setLayoutData(data);
}
// Single executor (and single thread) is used by all data generators,
// including the sum generator.
DsfExecutor executor = new DefaultDsfExecutor("Example executor");
// Create the data generator.
final IDataGenerator[] generators = new IDataGenerator[5];
for (int i = 0; i < generators.length; i++) {
generators[i] = new DataGeneratorWithExecutor(executor);
}
final IDataGenerator sumGenerator = new AsyncSumDataGenerator(executor, generators);
// Create the content provider which will populate the viewer.
AsyncSumDataViewer contentProvider = new AsyncSumDataViewer(tableViewer, generators, sumGenerator);
tableViewer.setContentProvider(contentProvider);
tableViewer.setInput(new Object());
// Open the shell and service the display dispatch loop until user
// closes the shell.
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
// The IDataGenerator.shutdown() method is asynchronous, this requires
// using a query again in order to wait for its completion.
Query<Object> shutdownQuery = new Query<Object>() {
@Override
protected void execute(DataRequestMonitor<Object> rm) {
CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm);
for (int i = 0; i < generators.length; i++) {
generators[i].shutdown(crm);
}
sumGenerator.shutdown(crm);
crm.setDoneCount(generators.length);
}
};
executor.execute(shutdownQuery);
try {
shutdownQuery.get();
} catch (Exception e) {
}
// Shut down the display.
font.dispose();
display.dispose();
}
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -36,135 +37,135 @@ import org.eclipse.core.runtime.Status;
*/ */
public class DataGeneratorCacheManager implements IDataGenerator.Listener { public class DataGeneratorCacheManager implements IDataGenerator.Listener {
/** Cache class for retrieving the data generator's count. */ /** Cache class for retrieving the data generator's count. */
private class CountCache extends RequestCache<Integer> { private class CountCache extends RequestCache<Integer> {
public CountCache() { public CountCache() {
super(fExecutor); super(fExecutor);
} }
@Override @Override
protected void retrieve(DataRequestMonitor<Integer> rm) { protected void retrieve(DataRequestMonitor<Integer> rm) {
fDataGenerator.getCount(rm); fDataGenerator.getCount(rm);
} }
/** /**
* Reset the cache when the count is changed. * Reset the cache when the count is changed.
*/ */
public void countChanged() { public void countChanged() {
// Make sure that if clients are currently waiting for a count, // Make sure that if clients are currently waiting for a count,
// they are notified of the update (their request monitors will be // they are notified of the update (their request monitors will be
// completed with an error). They shoudl then re-request data // completed with an error). They shoudl then re-request data
// from provider again. // from provider again.
setAndReset(null, new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Count changed")); setAndReset(null, new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Count changed"));
} }
} }
/** Cache class for retrieving the data generator's values. */ /** Cache class for retrieving the data generator's values. */
private class ValueCache extends RequestCache<Integer> { private class ValueCache extends RequestCache<Integer> {
private int fIndex; private int fIndex;
public ValueCache(int index) { public ValueCache(int index) {
super(fExecutor); super(fExecutor);
fIndex = index; fIndex = index;
} }
@Override @Override
protected void retrieve(org.eclipse.cdt.dsf.concurrent.DataRequestMonitor<Integer> rm) { protected void retrieve(org.eclipse.cdt.dsf.concurrent.DataRequestMonitor<Integer> rm) {
fDataGenerator.getValue(fIndex, rm); fDataGenerator.getValue(fIndex, rm);
}; };
/** /**
* @see CountCache#countChanged() * @see CountCache#countChanged()
*/ */
public void valueChanged() { public void valueChanged() {
setAndReset(null, new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Value changed")); setAndReset(null, new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Value changed"));
} }
} }
/** /**
* Executor used to synchronize data access in this cache manager. * Executor used to synchronize data access in this cache manager.
* It has to be the same executor that is used by the data generators in * It has to be the same executor that is used by the data generators in
* order to guarantee data consistency. * order to guarantee data consistency.
*/ */
private ImmediateInDsfExecutor fExecutor; private ImmediateInDsfExecutor fExecutor;
/** /**
* Data generator that this cache manager is a wrapper for. * Data generator that this cache manager is a wrapper for.
*/ */
private IDataGenerator fDataGenerator; private IDataGenerator fDataGenerator;
/** Cache for data generator's count */ /** Cache for data generator's count */
private CountCache fCountCache; private CountCache fCountCache;
/** /**
* Map of caches for retrieving values. Each value index has a separate * Map of caches for retrieving values. Each value index has a separate
* cache value object. * cache value object.
*/ */
private Map<Integer, ValueCache> fValueCaches = new HashMap<Integer, ValueCache>(); private Map<Integer, ValueCache> fValueCaches = new HashMap<Integer, ValueCache>();
public DataGeneratorCacheManager(ImmediateInDsfExecutor executor, IDataGenerator dataGenerator) { public DataGeneratorCacheManager(ImmediateInDsfExecutor executor, IDataGenerator dataGenerator) {
fExecutor = executor; fExecutor = executor;
fDataGenerator = dataGenerator; fDataGenerator = dataGenerator;
fDataGenerator.addListener(this); fDataGenerator.addListener(this);
} }
public void dispose() { public void dispose() {
fDataGenerator.removeListener(this); fDataGenerator.removeListener(this);
} }
/** /**
* Returns the data generator that this cache manager wraps. * Returns the data generator that this cache manager wraps.
*/ */
public IDataGenerator getDataGenerator() { public IDataGenerator getDataGenerator() {
return fDataGenerator; return fDataGenerator;
} }
/** /**
* Returns the cache for data generator count. * Returns the cache for data generator count.
*/ */
public ICache<Integer> getCount() { public ICache<Integer> getCount() {
if (fCountCache == null) { if (fCountCache == null) {
fCountCache = new CountCache(); fCountCache = new CountCache();
} }
return fCountCache; return fCountCache;
} }
/** /**
* Returns the cache for a value at given index. * Returns the cache for a value at given index.
* *
* @param index Index of value to return. * @param index Index of value to return.
* @return Cache object for given value. * @return Cache object for given value.
*/ */
public ICache<Integer> getValue(int index) { public ICache<Integer> getValue(int index) {
ValueCache value = fValueCaches.get(index); ValueCache value = fValueCaches.get(index);
if (value == null) { if (value == null) {
value = new ValueCache(index); value = new ValueCache(index);
fValueCaches.put(index, value); fValueCaches.put(index, value);
} }
return value; return value;
} }
@Override @Override
public void countChanged() { public void countChanged() {
// Reset the count cache and all the value caches. // Reset the count cache and all the value caches.
if (fCountCache != null) { if (fCountCache != null) {
fCountCache.countChanged(); fCountCache.countChanged();
} }
for (ValueCache value : fValueCaches.values()) { for (ValueCache value : fValueCaches.values()) {
value.valueChanged(); value.valueChanged();
} }
} }
@Override @Override
public void valuesChanged(Set<Integer> indexes) { public void valuesChanged(Set<Integer> indexes) {
// Reset selected value caches. // Reset selected value caches.
for (Integer index : indexes) { for (Integer index : indexes) {
ValueCache value = fValueCaches.get(index); ValueCache value = fValueCaches.get(index);
if (value != null) { if (value != null) {
value.valueChanged(); value.valueChanged();
} }
} }
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -60,409 +61,399 @@ import org.eclipse.cdt.examples.dsf.DsfExamplesPlugin;
//#endif //#endif
public class DataGeneratorWithExecutor implements IDataGenerator { public class DataGeneratorWithExecutor implements IDataGenerator {
// Request objects are used to serialize the interface calls into objects // Request objects are used to serialize the interface calls into objects
// which can then be pushed into a queue. // which can then be pushed into a queue.
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotationindicating allowed concurrency access // TODO Exercise 4 - Add an annotationindicating allowed concurrency access
// Hint: Request and its subclasses have all their fields declared as final. // Hint: Request and its subclasses have all their fields declared as final.
//#else //#else
//# @Immutable //# @Immutable
//#endif //#endif
abstract class Request { abstract class Request {
final RequestMonitor fRequestMonitor; final RequestMonitor fRequestMonitor;
Request(RequestMonitor rm) { Request(RequestMonitor rm) {
fRequestMonitor = rm; fRequestMonitor = rm;
rm.addCancelListener(new RequestMonitor.ICanceledListener() { rm.addCancelListener(new RequestMonitor.ICanceledListener() {
@Override @Override
public void requestCanceled(RequestMonitor rm) { public void requestCanceled(RequestMonitor rm) {
fExecutor.execute(new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fQueue.remove(Request.this); fQueue.remove(Request.this);
} }
}); });
} }
}); });
} }
} }
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @Immutable //# @Immutable
//#endif //#endif
class CountRequest extends Request { class CountRequest extends Request {
CountRequest(DataRequestMonitor<Integer> rm) { CountRequest(DataRequestMonitor<Integer> rm) {
super(rm); super(rm);
} }
} }
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @Immutable //# @Immutable
//#endif //#endif
class ItemRequest extends Request { class ItemRequest extends Request {
final int fIndex; final int fIndex;
ItemRequest(int index, DataRequestMonitor<Integer> rm) {
super(rm);
fIndex = index;
}
}
// The executor used to access all internal data of the generator. ItemRequest(int index, DataRequestMonitor<Integer> rm) {
//#ifdef exercises super(rm);
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) fIndex = index;
// indicating allowed thread access to this class/method/member }
// Hint: If a member does not have an annotation, the programmer can assume }
// that the concurrency rule that applies to the class also applies to this
// member.
//#endif
private DsfExecutor fExecutor;
// Main request queue of the data generator. The getValue(), getCount(), // The executor used to access all internal data of the generator.
// and shutdown() methods write into the queue, while the serviceQueue() //#ifdef exercises
// method reads from it. // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// The executor used to access all internal data of the generator. // indicating allowed thread access to this class/method/member
//#ifdef exercises // Hint: If a member does not have an annotation, the programmer can assume
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // that the concurrency rule that applies to the class also applies to this
// indicating allowed thread access to this class/method/member // member.
//#else //#endif
//# @ConfinedToDsfExecutor("fExecutor") private DsfExecutor fExecutor;
//#endif
private List<Request> fQueue = new LinkedList<Request>();
// List of listeners is not synchronized, it also has to be accessed // Main request queue of the data generator. The getValue(), getCount(),
// using the executor. // and shutdown() methods write into the queue, while the serviceQueue()
//#ifdef exercises // method reads from it.
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // The executor used to access all internal data of the generator.
// indicating allowed thread access to this class/method/member //#ifdef exercises
//#else // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
//# @ConfinedToDsfExecutor("fExecutor") // indicating allowed thread access to this class/method/member
//#endif //#else
private List<Listener> fListeners = new LinkedList<Listener>(); //# @ConfinedToDsfExecutor("fExecutor")
//#endif
private List<Request> fQueue = new LinkedList<Request>();
// Current number of elements in this generator. // List of listeners is not synchronized, it also has to be accessed
//#ifdef exercises // using the executor.
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) //#ifdef exercises
// indicating allowed thread access to this class/method/member // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
//#else // indicating allowed thread access to this class/method/member
//# @ConfinedToDsfExecutor("fExecutor") //#else
//#endif //# @ConfinedToDsfExecutor("fExecutor")
private int fCount = MIN_COUNT; //#endif
private List<Listener> fListeners = new LinkedList<Listener>();
// Counter used to determine when to reset the element count. // Current number of elements in this generator.
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private int fCountResetTrigger = 0; private int fCount = MIN_COUNT;
// Elements which were modified since the last reset. // Counter used to determine when to reset the element count.
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private Map<Integer, Integer> fChangedValues = private int fCountResetTrigger = 0;
new HashMap<Integer, Integer>();
public DataGeneratorWithExecutor() { // Elements which were modified since the last reset.
// Create the executor //#ifdef exercises
this(new DefaultDsfExecutor("Supplier Executor")); // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
} // indicating allowed thread access to this class/method/member
//#ifdef exercises //#else
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) //# @ConfinedToDsfExecutor("fExecutor")
// indicating allowed thread access to this class/method/member //#endif
//#endif private Map<Integer, Integer> fChangedValues = new HashMap<Integer, Integer>();
public DataGeneratorWithExecutor(DsfExecutor executor) {
// Create the executor
fExecutor = executor;
final Random rand = new Random();
// Schedule a runnable to make the random changes.
fExecutor.scheduleAtFixedRate(
new DsfRunnable() {
@Override
public void run() {
randomChanges();
}
},
rand.nextInt(RANDOM_CHANGE_INTERVAL),
RANDOM_CHANGE_INTERVAL, //Add a 10% variance to the interval.
TimeUnit.MILLISECONDS);
}
//#ifdef exercises public DataGeneratorWithExecutor() {
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // Create the executor
// indicating allowed thread access to this class/method/member this(new DefaultDsfExecutor("Supplier Executor"));
//#endif }
@Override
//#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member
//#endif
public DataGeneratorWithExecutor(DsfExecutor executor) {
// Create the executor
fExecutor = executor;
final Random rand = new Random();
// Schedule a runnable to make the random changes.
fExecutor.scheduleAtFixedRate(new DsfRunnable() {
@Override
public void run() {
randomChanges();
}
}, rand.nextInt(RANDOM_CHANGE_INTERVAL), RANDOM_CHANGE_INTERVAL, //Add a 10% variance to the interval.
TimeUnit.MILLISECONDS);
}
//#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member
//#endif
@Override
public void shutdown(final RequestMonitor rm) { public void shutdown(final RequestMonitor rm) {
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
// Empty the queue of requests and fail them. // Empty the queue of requests and fail them.
for (Request request : fQueue) { for (Request request : fQueue) {
request.fRequestMonitor.setStatus(new Status( request.fRequestMonitor.setStatus(
IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); request.fRequestMonitor.done();
request.fRequestMonitor.done(); }
} fQueue.clear();
fQueue.clear();
// Kill executor. // Kill executor.
fExecutor.shutdown(); fExecutor.shutdown();
rm.done(); rm.done();
} }
}); });
} catch (RejectedExecutionException e) { } catch (RejectedExecutionException e) {
rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); rm.done();
rm.done(); }
} }
}
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#endif //#endif
@Override @Override
public void getCount(final DataRequestMonitor<Integer> rm) { public void getCount(final DataRequestMonitor<Integer> rm) {
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fQueue.add(new CountRequest(rm)); fQueue.add(new CountRequest(rm));
serviceQueue(); serviceQueue();
} }
}); });
} catch (RejectedExecutionException e) { } catch (RejectedExecutionException e) {
rm.setStatus(new Status( rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.done();
"Supplier shut down")); }
rm.done(); }
}
}
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#endif //#endif
@Override @Override
public void getValue(final int index, final DataRequestMonitor<Integer> rm) { public void getValue(final int index, final DataRequestMonitor<Integer> rm) {
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fQueue.add(new ItemRequest(index, rm)); fQueue.add(new ItemRequest(index, rm));
serviceQueue(); serviceQueue();
} }
}); });
} catch (RejectedExecutionException e) { } catch (RejectedExecutionException e) {
rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); rm.done();
rm.done(); }
} }
}
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#endif //#endif
@Override @Override
public void addListener(final Listener listener) { public void addListener(final Listener listener) {
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fListeners.add(listener); fListeners.add(listener);
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#endif //#endif
@Override @Override
public void removeListener(final Listener listener) { public void removeListener(final Listener listener) {
try { try {
fExecutor.execute( new DsfRunnable() { fExecutor.execute(new DsfRunnable() {
@Override @Override
public void run() { public void run() {
fListeners.remove(listener); fListeners.remove(listener);
} }
}); });
} catch (RejectedExecutionException e) {} } catch (RejectedExecutionException e) {
} }
}
// Main processing function of this generator. // Main processing function of this generator.
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void serviceQueue() { private void serviceQueue() {
fExecutor.schedule( fExecutor.schedule(new DsfRunnable() {
new DsfRunnable() { @Override
@Override public void run() {
public void run() { doServiceQueue();
doServiceQueue(); }
} }, PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}, }
PROCESSING_DELAY, TimeUnit.MILLISECONDS);
}
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void doServiceQueue() { private void doServiceQueue() {
//#ifdef exercises //#ifdef exercises
// TODO Exercise 3 - Add logic to discard cancelled requests from queue. // TODO Exercise 3 - Add logic to discard cancelled requests from queue.
// Hint: Since serviceQueue() is called using the executor, and the // Hint: Since serviceQueue() is called using the executor, and the
// fQueue list can only be modified when running in the executor // fQueue list can only be modified when running in the executor
// thread. This method can safely iterate and modify fQueue without // thread. This method can safely iterate and modify fQueue without
// risk of race conditions or concurrent modification exceptions. // risk of race conditions or concurrent modification exceptions.
//#else //#else
//# for (Iterator<Request> requestItr = fQueue.iterator(); requestItr.hasNext();) { //# for (Iterator<Request> requestItr = fQueue.iterator(); requestItr.hasNext();) {
//# Request request = requestItr.next(); //# Request request = requestItr.next();
//# if (request.fRequestMonitor.isCanceled()) { //# if (request.fRequestMonitor.isCanceled()) {
//# request.fRequestMonitor.setStatus( //# request.fRequestMonitor.setStatus(
//# new Status(IStatus.CANCEL, DsfExamplesPlugin.PLUGIN_ID, "Request canceled")); //# new Status(IStatus.CANCEL, DsfExamplesPlugin.PLUGIN_ID, "Request canceled"));
//# request.fRequestMonitor.done(); //# request.fRequestMonitor.done();
//# requestItr.remove(); //# requestItr.remove();
//# } //# }
//# } //# }
//#endif //#endif
while (fQueue.size() != 0) { while (fQueue.size() != 0) {
// If there are requests to service, remove one from the queue and // If there are requests to service, remove one from the queue and
// schedule a runnable to process the request after a processing // schedule a runnable to process the request after a processing
// delay. // delay.
Request request = fQueue.remove(0); Request request = fQueue.remove(0);
if (request instanceof CountRequest) { if (request instanceof CountRequest) {
processCountRequest((CountRequest)request); processCountRequest((CountRequest) request);
} else if (request instanceof ItemRequest) { } else if (request instanceof ItemRequest) {
processItemRequest((ItemRequest)request); processItemRequest((ItemRequest) request);
} }
} }
} }
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void processCountRequest(CountRequest request) { private void processCountRequest(CountRequest request) {
@SuppressWarnings("unchecked") // Suppress warning about lost type info. @SuppressWarnings("unchecked") // Suppress warning about lost type info.
DataRequestMonitor<Integer> rm = DataRequestMonitor<Integer> rm = (DataRequestMonitor<Integer>) request.fRequestMonitor;
(DataRequestMonitor<Integer>)request.fRequestMonitor;
rm.setData(fCount); rm.setData(fCount);
rm.done(); rm.done();
} }
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void processItemRequest(ItemRequest request) { private void processItemRequest(ItemRequest request) {
@SuppressWarnings("unchecked") // Suppress warning about lost type info. @SuppressWarnings("unchecked") // Suppress warning about lost type info.
DataRequestMonitor<Integer> rm = DataRequestMonitor<Integer> rm = (DataRequestMonitor<Integer>) request.fRequestMonitor;
(DataRequestMonitor<Integer>)request.fRequestMonitor;
if (fChangedValues.containsKey(request.fIndex)) { if (fChangedValues.containsKey(request.fIndex)) {
rm.setData(fChangedValues.get(request.fIndex)); rm.setData(fChangedValues.get(request.fIndex));
} else { } else {
rm.setData(request.fIndex); rm.setData(request.fIndex);
} }
rm.done(); rm.done();
} }
/** /**
* This method simulates changes in the supplier's data set. * This method simulates changes in the supplier's data set.
*/ */
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void randomChanges() { private void randomChanges() {
// Once every number of changes, reset the count, the rest of the // Once every number of changes, reset the count, the rest of the
// times just change certain values. // times just change certain values.
if (++fCountResetTrigger % RANDOM_COUNT_CHANGE_INTERVALS == 0){ if (++fCountResetTrigger % RANDOM_COUNT_CHANGE_INTERVALS == 0) {
randomCountReset(); randomCountReset();
} else { } else {
randomDataChange(); randomDataChange();
} }
} }
/** /**
* Calculates new size for provider's data set. * Calculates new size for provider's data set.
*/ */
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void randomCountReset() { private void randomCountReset() {
// Calculate the new count. // Calculate the new count.
Random random = new java.util.Random(); Random random = new java.util.Random();
fCount = MIN_COUNT + random.nextInt(MAX_COUNT - MIN_COUNT); fCount = MIN_COUNT + random.nextInt(MAX_COUNT - MIN_COUNT);
// Reset the changed values. // Reset the changed values.
fChangedValues.clear(); fChangedValues.clear();
// Notify listeners // Notify listeners
for (Listener listener : fListeners) { for (Listener listener : fListeners) {
listener.countChanged(); listener.countChanged();
} }
} }
/** /**
* Invalidates a random range of indexes. * Invalidates a random range of indexes.
*/ */
//#ifdef exercises //#ifdef exercises
// TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor) // TODO Exercise 4 - Add an annotation (ThreadSafe/ConfinedToDsfExecutor)
// indicating allowed thread access to this class/method/member // indicating allowed thread access to this class/method/member
//#else //#else
//# @ConfinedToDsfExecutor("fExecutor") //# @ConfinedToDsfExecutor("fExecutor")
//#endif //#endif
private void randomDataChange() { private void randomDataChange() {
// Calculate the indexes to change. // Calculate the indexes to change.
Random random = new java.util.Random(); Random random = new java.util.Random();
Map<Integer, Integer> changed = new HashMap<Integer, Integer>(); Map<Integer, Integer> changed = new HashMap<Integer, Integer>();
for (int i = 0; i < fCount * RANDOM_CHANGE_SET_PERCENTAGE / 100; i++) { for (int i = 0; i < fCount * RANDOM_CHANGE_SET_PERCENTAGE / 100; i++) {
int randomIndex = random.nextInt(fCount); int randomIndex = random.nextInt(fCount);
int randomValue = random.nextInt(fCount); int randomValue = random.nextInt(fCount);
changed.put(randomIndex, randomValue); changed.put(randomIndex, randomValue);
} }
// Add the indexes to an overall set of changed indexes. // Add the indexes to an overall set of changed indexes.
fChangedValues.putAll(changed); fChangedValues.putAll(changed);
// Notify listeners // Notify listeners
for (Object listener : fListeners) { for (Object listener : fListeners) {
((Listener)listener).valuesChanged(changed.keySet()); ((Listener) listener).valuesChanged(changed.keySet());
} }
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -44,221 +45,208 @@ import org.eclipse.cdt.examples.dsf.DsfExamplesPlugin;
* synchronization. * synchronization.
* </p> * </p>
*/ */
public class DataGeneratorWithThread extends Thread public class DataGeneratorWithThread extends Thread implements IDataGenerator {
implements IDataGenerator
{
// Request objects are used to serialize the interface calls into objects // Request objects are used to serialize the interface calls into objects
// which can then be pushed into a queue. // which can then be pushed into a queue.
abstract class Request { abstract class Request {
final RequestMonitor fRequestMonitor; final RequestMonitor fRequestMonitor;
Request(RequestMonitor rm) { Request(RequestMonitor rm) {
fRequestMonitor = rm; fRequestMonitor = rm;
} }
} }
class CountRequest extends Request { class CountRequest extends Request {
CountRequest(DataRequestMonitor<Integer> rm) { CountRequest(DataRequestMonitor<Integer> rm) {
super(rm); super(rm);
} }
} }
class ItemRequest extends Request { class ItemRequest extends Request {
final int fIndex; final int fIndex;
ItemRequest(int index, DataRequestMonitor<Integer> rm) {
super(rm);
fIndex = index;
}
}
class ShutdownRequest extends Request { ItemRequest(int index, DataRequestMonitor<Integer> rm) {
ShutdownRequest(RequestMonitor rm) { super(rm);
super(rm); fIndex = index;
} }
} }
// Main request queue of the data generator. The getValue(), getCount(), class ShutdownRequest extends Request {
// and shutdown() methods write into the queue, while the run() method ShutdownRequest(RequestMonitor rm) {
// reads from it. super(rm);
private final BlockingQueue<Request> fQueue = }
new LinkedBlockingQueue<Request>(); }
// ListenerList class provides thread safety. // Main request queue of the data generator. The getValue(), getCount(),
private ListenerList<Listener> fListeners = new ListenerList<>(); // and shutdown() methods write into the queue, while the run() method
// reads from it.
private final BlockingQueue<Request> fQueue = new LinkedBlockingQueue<Request>();
// Current number of elements in this generator. // ListenerList class provides thread safety.
private int fCount = MIN_COUNT; private ListenerList<Listener> fListeners = new ListenerList<>();
// Counter used to determine when to reset the element count. // Current number of elements in this generator.
private int fCountResetTrigger = 0; private int fCount = MIN_COUNT;
// Elements which were modified since the last reset. // Counter used to determine when to reset the element count.
private Map<Integer, Integer> fChangedValues = private int fCountResetTrigger = 0;
Collections.synchronizedMap(new HashMap<Integer, Integer>());
// Used to determine when to make changes in data. // Elements which were modified since the last reset.
private long fLastChangeTime = System.currentTimeMillis(); private Map<Integer, Integer> fChangedValues = Collections.synchronizedMap(new HashMap<Integer, Integer>());
// Flag indicating when the generator has been shut down. // Used to determine when to make changes in data.
private AtomicBoolean fShutdown = new AtomicBoolean(false); private long fLastChangeTime = System.currentTimeMillis();
public DataGeneratorWithThread() { // Flag indicating when the generator has been shut down.
// Immediately kick off the request processing thread. private AtomicBoolean fShutdown = new AtomicBoolean(false);
start();
}
@Override public DataGeneratorWithThread() {
// Immediately kick off the request processing thread.
start();
}
@Override
public void shutdown(RequestMonitor rm) { public void shutdown(RequestMonitor rm) {
// Mark the generator as shut down. After the fShutdown flag is set, // Mark the generator as shut down. After the fShutdown flag is set,
// all new requests should be shut down. // all new requests should be shut down.
if (!fShutdown.getAndSet(true)) { if (!fShutdown.getAndSet(true)) {
fQueue.add(new ShutdownRequest(rm)); fQueue.add(new ShutdownRequest(rm));
} else { } else {
// //
rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); rm.done();
rm.done(); }
} }
}
@Override @Override
public void getCount(DataRequestMonitor<Integer> rm) { public void getCount(DataRequestMonitor<Integer> rm) {
if (!fShutdown.get()) { if (!fShutdown.get()) {
fQueue.add(new CountRequest(rm)); fQueue.add(new CountRequest(rm));
} else { } else {
rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); rm.done();
rm.done(); }
} }
}
@Override @Override
public void getValue(int index, DataRequestMonitor<Integer> rm) { public void getValue(int index, DataRequestMonitor<Integer> rm) {
if (!fShutdown.get()) { if (!fShutdown.get()) {
fQueue.add(new ItemRequest(index, rm)); fQueue.add(new ItemRequest(index, rm));
} else { } else {
rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, rm.setStatus(new Status(IStatus.ERROR, DsfExamplesPlugin.PLUGIN_ID, "Supplier shut down"));
"Supplier shut down")); rm.done();
rm.done(); }
} }
}
@Override @Override
public void addListener(Listener listener) { public void addListener(Listener listener) {
fListeners.add(listener); fListeners.add(listener);
} }
@Override @Override
public void removeListener(Listener listener) { public void removeListener(Listener listener) {
fListeners.remove(listener); fListeners.remove(listener);
} }
@Override @Override
public void run() { public void run() {
try { try {
while(true) { while (true) {
// Get the next request from the queue. The time-out // Get the next request from the queue. The time-out
// ensures that that the random changes get processed. // ensures that that the random changes get processed.
final Request request = fQueue.poll(100, TimeUnit.MILLISECONDS); final Request request = fQueue.poll(100, TimeUnit.MILLISECONDS);
// If a request was dequeued, process it. // If a request was dequeued, process it.
if (request != null) { if (request != null) {
// Simulate a processing delay. // Simulate a processing delay.
if (request instanceof CountRequest) { if (request instanceof CountRequest) {
processCountRequest((CountRequest)request); processCountRequest((CountRequest) request);
} else if (request instanceof ItemRequest) { } else if (request instanceof ItemRequest) {
processItemRequest((ItemRequest)request); processItemRequest((ItemRequest) request);
} else if (request instanceof ShutdownRequest) { } else if (request instanceof ShutdownRequest) {
// If shutting down, just break out of the while(true) // If shutting down, just break out of the while(true)
// loop and thread will exit. // loop and thread will exit.
request.fRequestMonitor.done(); request.fRequestMonitor.done();
break; break;
} }
} else { } else {
Thread.sleep(PROCESSING_DELAY); Thread.sleep(PROCESSING_DELAY);
} }
// Simulate data changes. // Simulate data changes.
randomChanges(); randomChanges();
} }
} } catch (InterruptedException x) {
catch (InterruptedException x) {} }
} }
private void processCountRequest(CountRequest request) { private void processCountRequest(CountRequest request) {
@SuppressWarnings("unchecked") // Suppress warning about lost type info. @SuppressWarnings("unchecked") // Suppress warning about lost type info.
DataRequestMonitor<Integer> rm = DataRequestMonitor<Integer> rm = (DataRequestMonitor<Integer>) request.fRequestMonitor;
(DataRequestMonitor<Integer>)request.fRequestMonitor;
rm.setData(fCount); rm.setData(fCount);
rm.done(); rm.done();
} }
private void processItemRequest(ItemRequest request) { private void processItemRequest(ItemRequest request) {
@SuppressWarnings("unchecked") // Suppress warning about lost type info. @SuppressWarnings("unchecked") // Suppress warning about lost type info.
DataRequestMonitor<Integer> rm = DataRequestMonitor<Integer> rm = (DataRequestMonitor<Integer>) request.fRequestMonitor;
(DataRequestMonitor<Integer>)request.fRequestMonitor;
if (fChangedValues.containsKey(request.fIndex)) { if (fChangedValues.containsKey(request.fIndex)) {
rm.setData(fChangedValues.get(request.fIndex)); rm.setData(fChangedValues.get(request.fIndex));
} else { } else {
rm.setData(request.fIndex); rm.setData(request.fIndex);
} }
rm.done(); rm.done();
} }
private void randomChanges() {
// Check if enough time is elapsed.
if (System.currentTimeMillis() > fLastChangeTime + RANDOM_CHANGE_INTERVAL) {
fLastChangeTime = System.currentTimeMillis();
private void randomChanges() { // Once every number of changes, reset the count, the rest of the
// Check if enough time is elapsed. // times just change certain values.
if (System.currentTimeMillis() > if (++fCountResetTrigger % RANDOM_COUNT_CHANGE_INTERVALS == 0) {
fLastChangeTime + RANDOM_CHANGE_INTERVAL) randomCountReset();
{ } else {
fLastChangeTime = System.currentTimeMillis(); randomDataChange();
}
}
}
// Once every number of changes, reset the count, the rest of the private void randomCountReset() {
// times just change certain values. // Calculate the new count.
if (++fCountResetTrigger % RANDOM_COUNT_CHANGE_INTERVALS == 0) { Random random = new java.util.Random();
randomCountReset(); fCount = MIN_COUNT + random.nextInt(MAX_COUNT - MIN_COUNT);
} else {
randomDataChange();
}
}
}
private void randomCountReset() { // Reset the changed values.
// Calculate the new count. fChangedValues.clear();
Random random = new java.util.Random();
fCount = MIN_COUNT + random.nextInt(MAX_COUNT - MIN_COUNT);
// Reset the changed values. // Notify listeners
fChangedValues.clear(); for (Object listener : fListeners.getListeners()) {
((Listener) listener).countChanged();
}
}
// Notify listeners private void randomDataChange() {
for (Object listener : fListeners.getListeners()) { // Calculate the indexes to change.
((Listener)listener).countChanged(); Random random = new java.util.Random();
} Map<Integer, Integer> changed = new HashMap<Integer, Integer>();
} for (int i = 0; i < fCount * RANDOM_CHANGE_SET_PERCENTAGE / 100; i++) {
int randomIndex = random.nextInt(fCount);
int randomValue = random.nextInt(fCount);
changed.put(randomIndex, randomValue);
}
private void randomDataChange() { // Add the indexes to an overall set of changed indexes.
// Calculate the indexes to change. fChangedValues.putAll(changed);
Random random = new java.util.Random();
Map<Integer, Integer> changed = new HashMap<Integer, Integer>();
for (int i = 0; i < fCount * RANDOM_CHANGE_SET_PERCENTAGE / 100; i++) {
int randomIndex = random.nextInt(fCount);
int randomValue = random.nextInt(fCount);
changed.put(randomIndex, randomValue);
}
// Add the indexes to an overall set of changed indexes. // Notify listeners
fChangedValues.putAll(changed); for (Object listener : fListeners.getListeners()) {
((Listener) listener).valuesChanged(changed.keySet());
// Notify listeners }
for (Object listener : fListeners.getListeners()) { }
((Listener)listener).valuesChanged(changed.keySet());
}
}
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -40,34 +41,36 @@ import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
//#endif //#endif
public interface IDataGenerator { public interface IDataGenerator {
// Constants which control the data generator behavior. // Constants which control the data generator behavior.
// Changing the count range can stress the scalability of the system, while // Changing the count range can stress the scalability of the system, while
// changing of the process delay and random change interval can stress // changing of the process delay and random change interval can stress
// its performance. // its performance.
final static int MIN_COUNT = 50; final static int MIN_COUNT = 50;
final static int MAX_COUNT = 100; final static int MAX_COUNT = 100;
final static int PROCESSING_DELAY = 500; final static int PROCESSING_DELAY = 500;
final static int RANDOM_CHANGE_INTERVAL = 4000; final static int RANDOM_CHANGE_INTERVAL = 4000;
final static int RANDOM_COUNT_CHANGE_INTERVALS = 5; final static int RANDOM_COUNT_CHANGE_INTERVALS = 5;
final static int RANDOM_CHANGE_SET_PERCENTAGE = 10; final static int RANDOM_CHANGE_SET_PERCENTAGE = 10;
// Listener interface that the view needs to implement to react
// to the changes in data.
public interface Listener {
void countChanged();
// Listener interface that the view needs to implement to react void valuesChanged(Set<Integer> indexes);
// to the changes in data. }
public interface Listener {
void countChanged();
void valuesChanged(Set<Integer> indexes);
}
// Data access methods. // Data access methods.
void getCount(DataRequestMonitor<Integer> rm); void getCount(DataRequestMonitor<Integer> rm);
void getValue(int index, DataRequestMonitor<Integer> rm);
// Method used to shutdown the data generator including any threads that void getValue(int index, DataRequestMonitor<Integer> rm);
// it may use.
void shutdown(RequestMonitor rm);
// Methods for registering change listeners. // Method used to shutdown the data generator including any threads that
void addListener(Listener listener); // it may use.
void removeListener(Listener listener); void shutdown(RequestMonitor rm);
// Methods for registering change listeners.
void addListener(Listener listener);
void removeListener(Listener listener);
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.dataviewer; package org.eclipse.cdt.examples.dsf.dataviewer;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.dataviewer.answers; //#package org.eclipse.cdt.examples.dsf.dataviewer.answers;
//#endif //#endif
@ -46,183 +47,174 @@ import org.eclipse.swt.widgets.Shell;
* {@link Query} object. * {@link Query} object.
* </p> * </p>
*/ */
public class SyncDataViewer public class SyncDataViewer implements IStructuredContentProvider, IDataGenerator.Listener {
implements IStructuredContentProvider, IDataGenerator.Listener // The viewer and generator that this content provider using.
{ final private TableViewer fViewer;
// The viewer and generator that this content provider using. final private IDataGenerator fDataGenerator;
final private TableViewer fViewer;
final private IDataGenerator fDataGenerator;
public SyncDataViewer(TableViewer viewer, IDataGenerator generator) { public SyncDataViewer(TableViewer viewer, IDataGenerator generator) {
fViewer = viewer; fViewer = viewer;
fDataGenerator = generator; fDataGenerator = generator;
fDataGenerator.addListener(this); fDataGenerator.addListener(this);
} }
@Override @Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// Not used // Not used
} }
@Override
@Override
public Object[] getElements(Object inputElement) { public Object[] getElements(Object inputElement) {
// Create the query object for reading data count. // Create the query object for reading data count.
Query<Integer> countQuery = new Query<Integer>() { Query<Integer> countQuery = new Query<Integer>() {
@Override @Override
protected void execute(DataRequestMonitor<Integer> rm) { protected void execute(DataRequestMonitor<Integer> rm) {
fDataGenerator.getCount(rm); fDataGenerator.getCount(rm);
} }
}; };
// Submit the query to be executed. A query implements a runnable // Submit the query to be executed. A query implements a runnable
// interface and it has to be executed in order to do its work. // interface and it has to be executed in order to do its work.
ImmediateExecutor.getInstance().execute(countQuery); ImmediateExecutor.getInstance().execute(countQuery);
int count = 0; int count = 0;
// Block until the query completes, which will happen when the request // Block until the query completes, which will happen when the request
// monitor of the execute() method is marked done. // monitor of the execute() method is marked done.
try { try {
count = countQuery.get(); count = countQuery.get();
} catch (Exception e) { } catch (Exception e) {
// InterruptedException and ExecutionException can be thrown here. // InterruptedException and ExecutionException can be thrown here.
// ExecutionException containing a CoreException will be thrown // ExecutionException containing a CoreException will be thrown
// if an error status is set to the Query's request monitor. // if an error status is set to the Query's request monitor.
return new Object[0]; return new Object[0];
} }
final int finalCount = count; final int finalCount = count;
Query<List<Integer>> valueQuery = new Query<List<Integer>>() { Query<List<Integer>> valueQuery = new Query<List<Integer>>() {
@Override @Override
protected void execute(final DataRequestMonitor<List<Integer>> rm) { protected void execute(final DataRequestMonitor<List<Integer>> rm) {
final Integer[] retVal = new Integer[finalCount]; final Integer[] retVal = new Integer[finalCount];
final CountingRequestMonitor crm = new CountingRequestMonitor( final CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm) {
ImmediateExecutor.getInstance(), rm) @Override
{ protected void handleSuccess() {
@Override rm.setData(Arrays.asList(retVal));
protected void handleSuccess() { rm.done();
rm.setData(Arrays.asList(retVal)); };
rm.done(); };
}; for (int i = 0; i < finalCount; i++) {
}; final int finalI = i;
for (int i = 0; i < finalCount; i++) { fDataGenerator.getValue(i, new DataRequestMonitor<Integer>(ImmediateExecutor.getInstance(), crm) {
final int finalI = i; @Override
fDataGenerator.getValue( protected void handleSuccess() {
i, retVal[finalI] = getData();
new DataRequestMonitor<Integer>( crm.done();
ImmediateExecutor.getInstance(), crm) }
{ });
@Override }
protected void handleSuccess() { crm.setDoneCount(finalCount);
retVal[finalI] = getData(); }
crm.done(); };
} ImmediateExecutor.getInstance().execute(valueQuery);
}); try {
} return valueQuery.get().toArray(new Integer[0]);
crm.setDoneCount(finalCount); } catch (Exception e) {
} }
}; return new Object[0];
ImmediateExecutor.getInstance().execute(valueQuery); }
try {
return valueQuery.get().toArray(new Integer[0]);
} catch (Exception e) {
}
return new Object[0];
}
@Override @Override
public void dispose() { public void dispose() {
fDataGenerator.removeListener(this); fDataGenerator.removeListener(this);
} }
@Override @Override
public void countChanged() { public void countChanged() {
// For any event from the generator, refresh the whole viewer. // For any event from the generator, refresh the whole viewer.
refreshViewer(); refreshViewer();
} }
@Override @Override
public void valuesChanged(Set<Integer> indexes) { public void valuesChanged(Set<Integer> indexes) {
// For any event from the generator, refresh the whole viewer. // For any event from the generator, refresh the whole viewer.
refreshViewer(); refreshViewer();
} }
private void refreshViewer() { private void refreshViewer() {
//#ifdef exercises //#ifdef exercises
// TODO Exercise 5 - Add a call to getElements() to force a deadlock. // TODO Exercise 5 - Add a call to getElements() to force a deadlock.
//#else //#else
//# getElements(null); //# getElements(null);
//#endif //#endif
// This method may be called on any thread, switch to the display // This method may be called on any thread, switch to the display
// thread before calling the viewer. // thread before calling the viewer.
Display display = fViewer.getControl().getDisplay(); Display display = fViewer.getControl().getDisplay();
display.asyncExec( new Runnable() { display.asyncExec(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!fViewer.getControl().isDisposed()) { if (!fViewer.getControl().isDisposed()) {
fViewer.refresh(); fViewer.refresh();
} }
} }
}); });
} }
/** /**
* The entry point for the example. * The entry point for the example.
* @param args Program arguments. * @param args Program arguments.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// Create the shell to hold the viewer. // Create the shell to hold the viewer.
Display display = new Display(); Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM); Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout()); shell.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_BOTH); GridData data = new GridData(GridData.FILL_BOTH);
shell.setLayoutData(data); shell.setLayoutData(data);
Font font = new Font(display, "Courier", 10, SWT.NORMAL); Font font = new Font(display, "Courier", 10, SWT.NORMAL);
// Create the table viewer. // Create the table viewer.
TableViewer tableViewer = new TableViewer(shell, SWT.BORDER); TableViewer tableViewer = new TableViewer(shell, SWT.BORDER);
tableViewer.getControl().setLayoutData(data); tableViewer.getControl().setLayoutData(data);
// Create the data generator. // Create the data generator.
//#ifdef exercises //#ifdef exercises
// TODO Exercise 5 - Use the DataGeneratorWithExecutor() instead. // TODO Exercise 5 - Use the DataGeneratorWithExecutor() instead.
final IDataGenerator generator = new DataGeneratorWithThread(); final IDataGenerator generator = new DataGeneratorWithThread();
//#else //#else
//# final IDataGenerator generator = new DataGeneratorWithExecutor(); //# final IDataGenerator generator = new DataGeneratorWithExecutor();
//#endif //#endif
// Create the content provider which will populate the viewer. // Create the content provider which will populate the viewer.
SyncDataViewer contentProvider = SyncDataViewer contentProvider = new SyncDataViewer(tableViewer, generator);
new SyncDataViewer(tableViewer, generator); tableViewer.setContentProvider(contentProvider);
tableViewer.setContentProvider(contentProvider); tableViewer.setInput(new Object());
tableViewer.setInput(new Object());
// Open the shell and service the display dispatch loop until user // Open the shell and service the display dispatch loop until user
// closes the shell. // closes the shell.
shell.open(); shell.open();
while (!shell.isDisposed()) { while (!shell.isDisposed()) {
if (!display.readAndDispatch()) if (!display.readAndDispatch())
display.sleep(); display.sleep();
} }
// The IDataGenerator.shutdown() method is asynchronous, this requires // The IDataGenerator.shutdown() method is asynchronous, this requires
// using a query again in order to wait for its completion. // using a query again in order to wait for its completion.
Query<Object> shutdownQuery = new Query<Object>() { Query<Object> shutdownQuery = new Query<Object>() {
@Override @Override
protected void execute(DataRequestMonitor<Object> rm) { protected void execute(DataRequestMonitor<Object> rm) {
generator.shutdown(rm); generator.shutdown(rm);
} }
}; };
ImmediateExecutor.getInstance().execute(shutdownQuery); ImmediateExecutor.getInstance().execute(shutdownQuery);
try { try {
shutdownQuery.get(); shutdownQuery.get();
} catch (Exception e) {} } catch (Exception e) {
}
// Shut down the display. // Shut down the display.
font.dispose(); font.dispose();
display.dispose(); display.dispose();
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.requestmonitor; package org.eclipse.cdt.examples.dsf.requestmonitor;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.requestmonitor.answers; //#package org.eclipse.cdt.examples.dsf.requestmonitor.answers;
//#endif //#endif
@ -28,20 +29,19 @@ import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor;
*/ */
public class Async2Plus2 { public class Async2Plus2 {
public static void main(String[] args) { public static void main(String[] args) {
Executor executor = ImmediateExecutor.getInstance(); Executor executor = ImmediateExecutor.getInstance();
DataRequestMonitor<Integer> rm = DataRequestMonitor<Integer> rm = new DataRequestMonitor<Integer>(executor, null) {
new DataRequestMonitor<Integer>(executor, null) { @Override
@Override protected void handleCompleted() {
protected void handleCompleted() { System.out.println("2 + 2 = " + getData());
System.out.println("2 + 2 = " + getData()); }
} };
}; asyncAdd(2, 2, rm);
asyncAdd(2, 2, rm); }
}
static void asyncAdd(int value1, int value2, DataRequestMonitor<Integer> rm) { static void asyncAdd(int value1, int value2, DataRequestMonitor<Integer> rm) {
rm.setData(value1 + value2); rm.setData(value1 + value2);
rm.done(); rm.done();
} }
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.requestmonitor; package org.eclipse.cdt.examples.dsf.requestmonitor;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.requestmonitor.answers; //#package org.eclipse.cdt.examples.dsf.requestmonitor.answers;
//#endif //#endif
@ -32,34 +33,34 @@ import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
*/ */
public class AsyncHelloWorld { public class AsyncHelloWorld {
public static void main(String[] args) { public static void main(String[] args) {
Executor executor = ImmediateExecutor.getInstance(); Executor executor = ImmediateExecutor.getInstance();
RequestMonitor rm = new RequestMonitor(executor, null); RequestMonitor rm = new RequestMonitor(executor, null);
asyncHelloWorld(rm); asyncHelloWorld(rm);
} }
static void asyncHelloWorld(RequestMonitor rm) { static void asyncHelloWorld(RequestMonitor rm) {
System.out.println("Hello world"); System.out.println("Hello world");
//#ifdef exercises //#ifdef exercises
// TODO Exercise 1: - Call the second async. "Hello world 2" method. // TODO Exercise 1: - Call the second async. "Hello world 2" method.
// Hint: Calling an asynchronous method requires passing to it a // Hint: Calling an asynchronous method requires passing to it a
// request monitor. A new request monitor can be constructed with // request monitor. A new request monitor can be constructed with
// a parent RequestMonitor as an argument argument. The parent gets // a parent RequestMonitor as an argument argument. The parent gets
// completed automatically when the lower level request monitor is // completed automatically when the lower level request monitor is
// completed. // completed.
rm.done(); rm.done();
//#else //#else
//# RequestMonitor rm2 = new RequestMonitor(ImmediateExecutor.getInstance(), rm); //# RequestMonitor rm2 = new RequestMonitor(ImmediateExecutor.getInstance(), rm);
//# asyncHelloWorld2(rm2); //# asyncHelloWorld2(rm2);
//#endif //#endif
} }
//#ifdef exercises //#ifdef exercises
// TODO: Exercise 1 - Add a second async. "Hello world 2" method. // TODO: Exercise 1 - Add a second async. "Hello world 2" method.
//#else //#else
//# static void asyncHelloWorld2(RequestMonitor rm) { //# static void asyncHelloWorld2(RequestMonitor rm) {
//# System.out.println("Hello world 2"); //# System.out.println("Hello world 2");
//# rm.done(); //# rm.done();
//# } //# }
//#endif //#endif
} }

View file

@ -14,6 +14,7 @@
//#ifdef exercises //#ifdef exercises
package org.eclipse.cdt.examples.dsf.requestmonitor; package org.eclipse.cdt.examples.dsf.requestmonitor;
//#else //#else
//#package org.eclipse.cdt.examples.dsf.requestmonitor.answers; //#package org.eclipse.cdt.examples.dsf.requestmonitor.answers;
//#endif //#endif
@ -33,117 +34,113 @@ import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
*/ */
public class AsyncQuicksort { public class AsyncQuicksort {
static Executor fgExecutor = ImmediateExecutor.getInstance(); static Executor fgExecutor = ImmediateExecutor.getInstance();
public static void main(String[] args) { public static void main(String[] args) {
final int[] array = {5, 7, 8, 3, 2, 1, 9, 5, 4}; final int[] array = { 5, 7, 8, 3, 2, 1, 9, 5, 4 };
System.out.println("To sort: " + Arrays.toString(array)); System.out.println("To sort: " + Arrays.toString(array));
asyncQuicksort( asyncQuicksort(array, 0, array.length - 1, new RequestMonitor(fgExecutor, null) {
array, 0, array.length - 1, @Override
new RequestMonitor(fgExecutor, null) { protected void handleCompleted() {
@Override System.out.println("Sorted: " + Arrays.toString(array));
protected void handleCompleted() { }
System.out.println("Sorted: " + Arrays.toString(array)); });
} }
});
}
static void asyncQuicksort(final int[] array, final int left, static void asyncQuicksort(final int[] array, final int left, final int right, final RequestMonitor rm) {
final int right, final RequestMonitor rm) if (right > left) {
{ int pivot = left;
if (right > left) { //#ifdef exercises
int pivot = left; // TODO: Exercise 2 - Convert the call to partition into an
//#ifdef exercises // asynchronous call to asyncPartition().
// TODO: Exercise 2 - Convert the call to partition into an // Hint: The rest of the code below should be executed inside
// asynchronous call to asyncPartition(). // the DataRequestMonitor.handleCompleted() overriding method.
// Hint: The rest of the code below should be executed inside int newPivot = partition(array, left, right, pivot);
// the DataRequestMonitor.handleCompleted() overriding method. printArray(array, left, right, newPivot);
int newPivot = partition(array, left, right, pivot);
printArray(array, left, right, newPivot);
CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm); CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm);
asyncQuicksort(array, left, newPivot - 1, countingRm); asyncQuicksort(array, left, newPivot - 1, countingRm);
asyncQuicksort(array, newPivot + 1, right, countingRm); asyncQuicksort(array, newPivot + 1, right, countingRm);
countingRm.setDoneCount(2); countingRm.setDoneCount(2);
//#else //#else
//# asyncPartition( //# asyncPartition(
//# array, left, right, pivot, //# array, left, right, pivot,
//# new DataRequestMonitor<Integer>(fgExecutor, rm) { //# new DataRequestMonitor<Integer>(fgExecutor, rm) {
//# @Override //# @Override
//# protected void handleCompleted() { //# protected void handleCompleted() {
//# int newPivot = getData(); //# int newPivot = getData();
//# printArray(array, left, right, newPivot); //# printArray(array, left, right, newPivot);
//# //#
//# CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm); //# CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm);
//# asyncQuicksort(array, left, newPivot - 1, countingRm); //# asyncQuicksort(array, left, newPivot - 1, countingRm);
//# asyncQuicksort(array, newPivot + 1, right, countingRm); //# asyncQuicksort(array, newPivot + 1, right, countingRm);
//# countingRm.setDoneCount(2); //# countingRm.setDoneCount(2);
//# } //# }
//# }); //# });
//#endif //#endif
} else { } else {
rm.done(); rm.done();
} }
} }
//#ifdef exercises //#ifdef exercises
// TODO Exercise 2 - Convert partition to an asynchronous method. // TODO Exercise 2 - Convert partition to an asynchronous method.
// Hint: a DataRequestMonitor<Integer> should be used to carry the // Hint: a DataRequestMonitor<Integer> should be used to carry the
// return value to the caller. // return value to the caller.
static int partition(int[] array, int left, int right, int pivot) static int partition(int[] array, int left, int right, int pivot)
//#else //#else
//# static void asyncPartition(int[] array, int left, int right, int pivot, DataRequestMonitor<Integer> rm) //# static void asyncPartition(int[] array, int left, int right, int pivot, DataRequestMonitor<Integer> rm)
//#endif //#endif
{ {
int pivotValue = array[pivot]; int pivotValue = array[pivot];
array[pivot] = array[right]; array[pivot] = array[right];
array[right] = pivotValue; array[right] = pivotValue;
int store = left; int store = left;
for (int i = left; i < right; i++) { for (int i = left; i < right; i++) {
if (array[i] <= pivotValue) { if (array[i] <= pivotValue) {
int tmp = array[store]; int tmp = array[store];
array[store] = array[i]; array[store] = array[i];
array[i] = tmp; array[i] = tmp;
store++; store++;
} }
} }
array[right] = array[store]; array[right] = array[store];
array[store] = pivotValue; array[store] = pivotValue;
//#ifdef exercises //#ifdef exercises
// TODO: Request Monitors Exercise 2 - Return the data to caller using // TODO: Request Monitors Exercise 2 - Return the data to caller using
// a request monitor. // a request monitor.
return store; return store;
//#else //#else
//# // Java 5 automatically converts the int type of the store variable //# // Java 5 automatically converts the int type of the store variable
//# // to an Integer object. //# // to an Integer object.
//# rm.setData(store); //# rm.setData(store);
//# rm.done(); //# rm.done();
//#endif //#endif
} }
static void printArray(int[] array, int left, int right, int pivot) { static void printArray(int[] array, int left, int right, int pivot) {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
for (int i = 0; i < array.length; i++ ) { for (int i = 0; i < array.length; i++) {
if (i == left) { if (i == left) {
buffer.append('>'); buffer.append('>');
} else if (i == pivot) { } else if (i == pivot) {
buffer.append('-'); buffer.append('-');
} else { } else {
buffer.append(' '); buffer.append(' ');
} }
buffer.append(array[i]); buffer.append(array[i]);
if (i == right) { if (i == right) {
buffer.append('<'); buffer.append('<');
} else if (i == pivot) { } else if (i == pivot) {
buffer.append('-'); buffer.append('-');
} else { } else {
buffer.append(' '); buffer.append(' ');
} }
} }
System.out.println(buffer); System.out.println(buffer);
} }
} }

View file

@ -462,8 +462,7 @@ abstract public class FormattedValueTests extends TestCase
ArrayList<ElementFormatSetting> elementFormats1 = new ArrayList<>(map1.values()); ArrayList<ElementFormatSetting> elementFormats1 = new ArrayList<>(map1.values());
HashMap<String, ElementFormatSetting> expMap1 = new HashMap<>(); HashMap<String, ElementFormatSetting> expMap1 = new HashMap<>();
makeElementFormatSetting(fViewer, TreePath.EMPTY, format1, depth, 0, expMap1); makeElementFormatSetting(fViewer, TreePath.EMPTY, format1, depth, 0, expMap1);
ArrayList<ElementFormatSetting> expectElementFormats1 = new ArrayList<>( ArrayList<ElementFormatSetting> expectElementFormats1 = new ArrayList<>(expMap1.values());
expMap1.values());
vmListenerLevel = depth; vmListenerLevel = depth;
setFormatAndValidate(preferenceFormat, elementFormats1, expectElementFormats1, true, false, false); setFormatAndValidate(preferenceFormat, elementFormats1, expectElementFormats1, true, false, false);
@ -474,8 +473,7 @@ abstract public class FormattedValueTests extends TestCase
ArrayList<ElementFormatSetting> elementFormats2 = new ArrayList<>(map2.values()); ArrayList<ElementFormatSetting> elementFormats2 = new ArrayList<>(map2.values());
HashMap<String, ElementFormatSetting> expMap2 = new HashMap<>(); HashMap<String, ElementFormatSetting> expMap2 = new HashMap<>();
makeElementFormatSetting(fViewer, TreePath.EMPTY, format2, depth, 0, expMap2); makeElementFormatSetting(fViewer, TreePath.EMPTY, format2, depth, 0, expMap2);
ArrayList<ElementFormatSetting> expectElementFormats2 = new ArrayList<>( ArrayList<ElementFormatSetting> expectElementFormats2 = new ArrayList<>(expMap2.values());
expMap2.values());
setFormatAndValidate(preferenceFormat, elementFormats2, expectElementFormats2, true, true, false); setFormatAndValidate(preferenceFormat, elementFormats2, expectElementFormats2, true, true, false);
// Generate an event which will cause all cache entries to be marked dirty. // Generate an event which will cause all cache entries to be marked dirty.
@ -491,8 +489,7 @@ abstract public class FormattedValueTests extends TestCase
ArrayList<ElementFormatSetting> elementFormats3 = new ArrayList<>(map3.values()); ArrayList<ElementFormatSetting> elementFormats3 = new ArrayList<>(map3.values());
HashMap<String, ElementFormatSetting> expMap3 = new HashMap<>(); HashMap<String, ElementFormatSetting> expMap3 = new HashMap<>();
makeElementFormatSetting(fViewer, TreePath.EMPTY, format3, depth, 0, expMap3); makeElementFormatSetting(fViewer, TreePath.EMPTY, format3, depth, 0, expMap3);
ArrayList<ElementFormatSetting> expectElementFormats3 = new ArrayList<>( ArrayList<ElementFormatSetting> expectElementFormats3 = new ArrayList<>(expMap3.values());
expMap3.values());
setFormatAndValidate(preferenceFormat, elementFormats3, expectElementFormats3, true, true, true); setFormatAndValidate(preferenceFormat, elementFormats3, expectElementFormats3, true, true, true);
} }
} }

View file

@ -476,8 +476,7 @@ public class GoToAddressBarWidget {
String id = UNKNOWN_CONTEXT_ID; String id = UNKNOWN_CONTEXT_ID;
if (context instanceof IAdaptable) { if (context instanceof IAdaptable) {
IAdaptable adaptable = (IAdaptable) context; IAdaptable adaptable = (IAdaptable) context;
IRecurringDebugContext recurringDebugContext = adaptable IRecurringDebugContext recurringDebugContext = adaptable.getAdapter(IRecurringDebugContext.class);
.getAdapter(IRecurringDebugContext.class);
if (recurringDebugContext != null) { if (recurringDebugContext != null) {
try { try {
id = recurringDebugContext.getContextID(); id = recurringDebugContext.getContextID();

View file

@ -660,7 +660,6 @@ public class MemoryBrowser extends ViewPart
label += ' ' + renderingType; label += ' ' + renderingType;
// Allow the memory block to customize the label. The platform's // Allow the memory block to customize the label. The platform's
// Memory view support this (it was done in the call to // Memory view support this (it was done in the call to
// rendering.getLabel() above) // rendering.getLabel() above)
@ -1412,8 +1411,7 @@ public class MemoryBrowser extends ViewPart
if (retrieval instanceof IMemoryBlockRetrievalExtension) { if (retrieval instanceof IMemoryBlockRetrievalExtension) {
retrievalExtension = (IMemoryBlockRetrievalExtension) retrieval; retrievalExtension = (IMemoryBlockRetrievalExtension) retrieval;
} else if (retrieval instanceof IAdaptable) { } else if (retrieval instanceof IAdaptable) {
retrievalExtension = ((IAdaptable) retrieval) retrievalExtension = ((IAdaptable) retrieval).getAdapter(IMemoryBlockRetrievalExtension.class);
.getAdapter(IMemoryBlockRetrievalExtension.class);
} }
if (retrievalExtension != null) { if (retrievalExtension != null) {
if (retrievalExtension instanceof IMemorySpaceAwareMemoryBlockRetrieval) { if (retrievalExtension instanceof IMemorySpaceAwareMemoryBlockRetrieval) {

View file

@ -42,10 +42,8 @@ public final class QMakeEnvInfo {
Collection<IFile> sensitiveFiles) { Collection<IFile> sensitiveFiles) {
this.proFile = proFile; this.proFile = proFile;
this.qmakeFilePath = qmakeFilePath; this.qmakeFilePath = qmakeFilePath;
this.environment = environment != null ? new HashMap<>(environment) this.environment = environment != null ? new HashMap<>(environment) : Collections.<String, String>emptyMap();
: Collections.<String, String>emptyMap(); this.sensitiveFiles = sensitiveFiles != null ? new HashSet<>(sensitiveFiles) : Collections.<IFile>emptySet();
this.sensitiveFiles = sensitiveFiles != null ? new HashSet<>(sensitiveFiles)
: Collections.<IFile>emptySet();
} }
/** /**

View file

@ -61,8 +61,7 @@ public final class QMakeInfo implements IQMakeInfo {
this.qtVersion = QMakeVersion.create(queryMap.get(QMakeParser.KEY_QT_VERSION)); this.qtVersion = QMakeVersion.create(queryMap.get(QMakeParser.KEY_QT_VERSION));
List<String> tmpQtImportPaths = new ArrayList<>( List<String> tmpQtImportPaths = new ArrayList<>(
QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_IMPORTS)); QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_IMPORTS));
List<String> tmpQtQmlPaths = new ArrayList<>( List<String> tmpQtQmlPaths = new ArrayList<>(QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_QML));
QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_QML));
this.qtDocPath = QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_DOCS); this.qtDocPath = QMakeParser.singleValue(queryMap, QMakeParser.KEY_QT_INSTALL_DOCS);
this.involvedQMakeFiles = QMakeParser.qmake3DecodeValueList(proMap, this.involvedQMakeFiles = QMakeParser.qmake3DecodeValueList(proMap,

View file

@ -76,8 +76,7 @@ public class QtPDOMQObject extends AbstractQtPDOMClass {
// Store the array into the Database. // Store the array into the Database.
long arrayRec = getDB().getRecPtr(Field.ClassInfos.getRecord(record)); long arrayRec = getDB().getRecPtr(Field.ClassInfos.getRecord(record));
QtPDOMArray<ClassInfo> pdomArray = new QtPDOMArray<>(getQtLinkage(), ClassInfo.Codec, QtPDOMArray<ClassInfo> pdomArray = new QtPDOMArray<>(getQtLinkage(), ClassInfo.Codec, arrayRec);
arrayRec);
arrayRec = pdomArray.set(array); arrayRec = pdomArray.set(array);
// Update the record that is stored in the receiver's field. // Update the record that is stored in the receiver's field.
@ -89,8 +88,7 @@ public class QtPDOMQObject extends AbstractQtPDOMClass {
// Read the array from the Database and insert the elements into the Map that is to be returned. // Read the array from the Database and insert the elements into the Map that is to be returned.
long arrayRec = getDB().getRecPtr(Field.ClassInfos.getRecord(record)); long arrayRec = getDB().getRecPtr(Field.ClassInfos.getRecord(record));
QtPDOMArray<ClassInfo> pdomArray = new QtPDOMArray<>(getQtLinkage(), ClassInfo.Codec, QtPDOMArray<ClassInfo> pdomArray = new QtPDOMArray<>(getQtLinkage(), ClassInfo.Codec, arrayRec);
arrayRec);
ClassInfo[] array = pdomArray.get(); ClassInfo[] array = pdomArray.get();
if (array == null) if (array == null)

View file

@ -72,8 +72,7 @@ public class TestingSession implements ITestingSession {
* statistics without model scanning. * statistics without model scanning.
* *
*/ */
private Map<ITestItem.Status, Integer> statusCounters = new EnumMap<>( private Map<ITestItem.Status, Integer> statusCounters = new EnumMap<>(ITestItem.Status.class);
ITestItem.Status.class);
/** /**
* The flag stores whether the testing session contains errors at the * The flag stores whether the testing session contains errors at the