Java Code Examples for java.util.IdentityHashMap

The following examples show how to use java.util.IdentityHashMap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: streamsupport   Author: streamsupport   File: MapWithCollisionsProviders.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static <T> Collection<Object[]> makeMapsMoreTypes(String desc,
                                                          T[] keys,
                                                          T val) {
    Collection<Object[]> cases = new ArrayList<>();
    cases.add(createCase("Hashtable with " + desc,
                         new Hashtable<>(), keys, val));
    cases.add(createCase("IdentityHashMap with " + desc,
                         new IdentityHashMap<>(), keys, val));
    cases.add(createCase("TreeMap with " + desc,
                         new TreeMap<>(), keys, val));
    cases.add(createCase("WeakHashMap with " + desc,
                         new WeakHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentHashMap with " + desc,
                         new ConcurrentHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentSkipListMap with " + desc,
                         new ConcurrentSkipListMap<>(), keys, val));
    return cases;
}
 
Example #2
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Iterator<Map.Entry<String, String>> entrySetIterator =
        identityHashMap.entrySet().iterator();
    Map.Entry<String, String> entry = entrySetIterator.next();

    entrySetIterator.remove();

    try {
        entry.getKey();
        throw new RuntimeException("Test FAILED: Entry not invalidated by removal.");
    } catch (Exception e) { }
}
 
Example #3
Source Project: vespa   Author: vespa-engine   File: ListMapTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAnotherImplementation() {
    ListMap<String, String> stringMap = new ListMap<>(IdentityHashMap.class);
    String foo = "foo";
    String bar = "bar";
    String far = "far";
    String rab = "rab";

    stringMap.put(foo, bar);
    stringMap.put(foo, far);
    stringMap.put(bar, rab);

    List<String> fooValues = stringMap.get(new String("foo"));
    assertEquals(0, fooValues.size());
    fooValues = stringMap.get(foo);
    assertEquals(2, fooValues.size());
    assertEquals("bar", fooValues.get(0));
    assertEquals("far", fooValues.get(1));


    List<String> barValues = stringMap.get(new String("bar"));
    assertEquals(0, barValues.size());
    barValues = stringMap.get(bar);
    assertEquals(1, barValues.size());
    assertEquals("rab", barValues.get(0));
}
 
Example #4
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: DistinctEntrySetElements.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = identityHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    // NB: These comparisons are valid in this case because none of the
    //     keys put into 'identityHashMap' above are equal to any other.
    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example #5
Source Project: avro-util   Author: linkedin   File: AvroSchemaUtil.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static void traverseSchema(Schema schema, SchemaVisitor visitor, IdentityHashMap<Object, Boolean> visited) {
  if (visited.put(schema, Boolean.TRUE) != null) {
    return; //been there, done that
  }
  visitor.visitSchema(schema);
  switch (schema.getType()) {
    case UNION:
      for (Schema unionBranch : schema.getTypes()) {
        traverseSchema(unionBranch, visitor, visited);
      }
      return;
    case ARRAY:
      traverseSchema(schema.getElementType(), visitor, visited);
      return;
    case MAP:
      traverseSchema(schema.getValueType(), visitor, visited);
      return;
    case RECORD:
      for (Schema.Field field : schema.getFields()) {
        visitor.visitField(field);
        traverseSchema(field.schema(), visitor, visited);
      }
      break;
    default:
  }
}
 
Example #6
Source Project: pcgen   Author: PCGen   File: BonusManager.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private Map<BonusObj, Object> getTempBonuses()
{
	Map<BonusObj, Object> map = new IdentityHashMap<>();
	getFilteredTempBonusList().forEach((bonus, value) -> {
		pc.setApplied(bonus, false);

		Object source = value.source;
		CDOMObject cdomsource = (source instanceof CDOMObject) ? (CDOMObject) source : null;
		if (bonus.qualifies(pc, cdomsource))
		{
			pc.setApplied(bonus, true);
		}

		if (pc.isApplied(bonus))
		{
			map.put(bonus, source);
		}
	});
	return map;
}
 
Example #7
Source Project: syncer   Author: zzt93   File: SyncDeserializer.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static EventDeserializer defaultDeserializer() {
  Map<Long, TableMapEventData> tableMapEventByTableId = new HashMap<>();
  Map<EventType, EventDataDeserializer> eventDataDeserializers = new IdentityHashMap<>();
  eventDataDeserializers.put(EventType.WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.EXT_WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.QUERY, new QueryEventDataDeserializer());
  eventDataDeserializers.put(EventType.TABLE_MAP, new TableMapEventDataDeserializer());

  return new EventDeserializer(new EventHeaderV4Deserializer(), new NullEventDataDeserializer(),
      eventDataDeserializers, tableMapEventByTableId);
}
 
Example #8
Source Project: vespa   Author: vespa-engine   File: SpanTree.java    License: Apache License 2.0 5 votes vote down vote up
private static IdentityHashMap<SpanNode, Integer> getSpanNodes(SpanTree otherToCopy) {
    IdentityHashMap<SpanNode, Integer> map = new IdentityHashMap<SpanNode, Integer>();
    int spanNodeCounter = 0;
    map.put(otherToCopy.getRoot(), spanNodeCounter++);
    Iterator<SpanNode> it = otherToCopy.getRoot().childIteratorRecursive();
    while (it.hasNext()) {
        map.put(it.next(), spanNodeCounter++);
    }
    return map;
}
 
Example #9
Source Project: j2objc   Author: google   File: RetainedWithTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMapChildren() {
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new IdentityHashMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new WeakHashMap<>();
    }
  });
  new MapTest<Color>().run(new MapFactory<Color>(Color.RED) {
    public Map<Color, ValueType> newMap() {
      return new EnumMap<>(Color.class);
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new HashMap<>();
    }
  });
  new MapTest<Integer>().run(new MapFactory<Integer>(5) {
    public Map<Integer, ValueType> newMap() {
      return new TreeMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new Hashtable<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new ConcurrentHashMap<>();
    }
  });
}
 
Example #10
Source Project: Telegram-FOSS   Author: Telegram-FOSS-Team   File: MergingMediaPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
public MergingMediaPeriod(CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    MediaPeriod... periods) {
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.periods = periods;
  childrenPendingPreparation = new ArrayList<>();
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamPeriodIndices = new IdentityHashMap<>();
}
 
Example #11
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: Capacity.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
Example #12
Source Project: gemfirexd-oss   Author: gemxd   File: OffHeapValidationJUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
private void putIdentityHashMap(Region<Object, Object> region, List<ExpectedValues> expected) {
  String key = "keyIdentityHashMap";
  IdentityHashMap<Object,Object> value = new IdentityHashMap<Object,Object>();
  value.put("1", "string 1");
  value.put("2", "string 2");
  region.put(key, value);
  expected.add(new ExpectedValues(value, 40, "java.util.IdentityHashMap", -1, getMemoryAddress(region, key), 1, 0, false, true));
}
 
Example #13
Source Project: NewsMe   Author: iQuick   File: GetBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GetBuilder addParams(String key, String val)
{
    if (this.params == null)
    {
        params = new IdentityHashMap<>();
    }
    params.put(key, val);
    return this;
}
 
Example #14
Source Project: servicecomb-java-chassis   Author: apache   File: TestDefaultTcpServerMetrics.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createMetrics() {
  Map<Object, Object> instances = new IdentityHashMap<>();
  instances.put(metrics_listen1_server1, null);
  instances.put(metrics_listen1_server2, null);
  instances.put(metrics_listen2_server1, null);
  instances.put(metrics_listen2_server2, null);
  Assert.assertEquals(4, instances.size());

  Assert.assertSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen1_server2.getEndpointMetric());
  Assert.assertNotSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen2_server1.getEndpointMetric());
  Assert.assertSame(metrics_listen2_server1.getEndpointMetric(), metrics_listen2_server2.getEndpointMetric());
}
 
Example #15
Source Project: lucene-solr   Author: apache   File: PerFieldDocValuesFormat.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void merge(MergeState mergeState) throws IOException {
  Map<DocValuesConsumer, Collection<String>> consumersToField = new IdentityHashMap<>();

  // Group each consumer by the fields it handles
  for (FieldInfo fi : mergeState.mergeFieldInfos) {
    if (fi.getDocValuesType() == DocValuesType.NONE) {
      continue;
    }
    // merge should ignore current format for the fields being merged
    DocValuesConsumer consumer = getInstance(fi, true);
    Collection<String> fieldsForConsumer = consumersToField.get(consumer);
    if (fieldsForConsumer == null) {
      fieldsForConsumer = new ArrayList<>();
      consumersToField.put(consumer, fieldsForConsumer);
    }
    fieldsForConsumer.add(fi.name);
  }

  // Delegate the merge to the appropriate consumer
  PerFieldMergeState pfMergeState = new PerFieldMergeState(mergeState);
  try {
    for (Map.Entry<DocValuesConsumer, Collection<String>> e : consumersToField.entrySet()) {
      e.getKey().merge(pfMergeState.apply(e.getValue()));
    }
  } finally {
    pfMergeState.reset();
  }
}
 
Example #16
Source Project: pcgen   Author: PCGen   File: TotalSkillRankFacet.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<Skill, Double> getConstructingInfo(CharID id)
{
	Map<Skill, Double> map = getInfo(id);
	if (map == null)
	{
		map = new IdentityHashMap<>();
		setCache(id, map);
	}
	return map;
}
 
Example #17
Source Project: liblevenshtein-java   Author: universal-automata   File: ProtobufSerializer.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the dictionary of the prototype.
 * @param proto Prototype of the dictionary.
 * @return Dictionary of the prototype.
 */
protected SortedDawg modelOf(final LibLevenshteinProtos.Dawg proto) {
  final Map<LibLevenshteinProtos.DawgNode, DawgNode> nodes =
    new IdentityHashMap<>();
  final DawgNode root = modelOf(proto.getRoot(), nodes);
  return new SortedDawg(proto.getSize(), root);
}
 
Example #18
Source Project: Telegram   Author: DrKLO   File: HlsMediaPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an HLS media period.
 *
 * @param extractorFactory An {@link HlsExtractorFactory} for {@link Extractor}s for the segments.
 * @param playlistTracker A tracker for HLS playlists.
 * @param dataSourceFactory An {@link HlsDataSourceFactory} for {@link DataSource}s for segments
 *     and keys.
 * @param mediaTransferListener The transfer listener to inform of any media data transfers. May
 *     be null if no listener is available.
 * @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
 * @param eventDispatcher A dispatcher to notify of events.
 * @param allocator An {@link Allocator} from which to obtain media buffer allocations.
 * @param compositeSequenceableLoaderFactory A factory to create composite {@link
 *     SequenceableLoader}s for when this media source loads data from multiple streams.
 * @param allowChunklessPreparation Whether chunkless preparation is allowed.
 * @param useSessionKeys Whether to use #EXT-X-SESSION-KEY tags.
 */
public HlsMediaPeriod(
    HlsExtractorFactory extractorFactory,
    HlsPlaylistTracker playlistTracker,
    HlsDataSourceFactory dataSourceFactory,
    @Nullable TransferListener mediaTransferListener,
    LoadErrorHandlingPolicy loadErrorHandlingPolicy,
    EventDispatcher eventDispatcher,
    Allocator allocator,
    CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    boolean allowChunklessPreparation,
    @HlsMetadataType int metadataType,
    boolean useSessionKeys) {
  this.extractorFactory = extractorFactory;
  this.playlistTracker = playlistTracker;
  this.dataSourceFactory = dataSourceFactory;
  this.mediaTransferListener = mediaTransferListener;
  this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
  this.eventDispatcher = eventDispatcher;
  this.allocator = allocator;
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.allowChunklessPreparation = allowChunklessPreparation;
  this.metadataType = metadataType;
  this.useSessionKeys = useSessionKeys;
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamWrapperIndices = new IdentityHashMap<>();
  timestampAdjusterProvider = new TimestampAdjusterProvider();
  sampleStreamWrappers = new HlsSampleStreamWrapper[0];
  enabledSampleStreamWrappers = new HlsSampleStreamWrapper[0];
  manifestUrlIndicesPerWrapper = new int[0][];
  eventDispatcher.mediaPeriodCreated();
}
 
Example #19
Source Project: treelayout   Author: abego   File: TreeLayout.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a TreeLayout for a given tree.
 * <p>
 * In addition to the tree the {@link NodeExtentProvider} and the
 * {@link Configuration} must be given.
 * 
    * @param tree &nbsp;
    * @param nodeExtentProvider &nbsp;
    * @param configuration &nbsp;
    * @param useIdentity
 *            [default: false] when true, identity ("==") is used instead of
 *            equality ("equals(...)") when checking nodes. Within a tree
 *            each node must only exist once (using this check).
 */
public TreeLayout(TreeForTreeLayout<TreeNode> tree,
		NodeExtentProvider<TreeNode> nodeExtentProvider,
		Configuration<TreeNode> configuration, boolean useIdentity) {
	this.tree = tree;
	this.nodeExtentProvider = nodeExtentProvider;
	this.configuration = configuration;
	this.useIdentity = useIdentity;

	if (this.useIdentity) {
		this.mod = new IdentityHashMap<TreeNode, Double>();
		this.thread = new IdentityHashMap<TreeNode, TreeNode>();
		this.prelim = new IdentityHashMap<TreeNode, Double>();
		this.change = new IdentityHashMap<TreeNode, Double>();
		this.shift = new IdentityHashMap<TreeNode, Double>();
		this.ancestor = new IdentityHashMap<TreeNode, TreeNode>();
		this.number = new IdentityHashMap<TreeNode, Integer>();
		this.positions = new IdentityHashMap<TreeNode, Point2D>();
	} else {
		this.mod = new HashMap<TreeNode, Double>();
		this.thread = new HashMap<TreeNode, TreeNode>();
		this.prelim = new HashMap<TreeNode, Double>();
		this.change = new HashMap<TreeNode, Double>();
		this.shift = new HashMap<TreeNode, Double>();
		this.ancestor = new HashMap<TreeNode, TreeNode>();
		this.number = new HashMap<TreeNode, Integer>();
		this.positions = new HashMap<TreeNode, Point2D>();
	}
	
	// No need to explicitly set mod, thread and ancestor as their getters
	// are taking care of the initial values. This avoids a full tree walk
	// through and saves some memory as no entries are added for
	// "initial values".

	TreeNode r = tree.getRoot();
	firstWalk(r, null);
	calcSizeOfLevels(r, 0);
	secondWalk(r, -getPrelim(r), 0, 0);
}
 
Example #20
Source Project: netbeans   Author: apache   File: ClusteredIndexablesCacheTest.java    License: Apache License 2.0 5 votes vote down vote up
private void globalPathRegistry_register(String id, ClassPath [] classpaths) {
    Map<ClassPath,Void> map = registeredClasspaths.get(id);
    if (map == null) {
        map = new IdentityHashMap<ClassPath, Void>();
        registeredClasspaths.put(id, map);
    }
    for (ClassPath cp :  classpaths) {
        map.put(cp,null);
    }
    GlobalPathRegistry.getDefault().register(id, classpaths);
}
 
Example #21
Source Project: pcgen   Author: PCGen   File: BonusManager.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<BonusObj, Object> getAllActiveBonuses()
{
	Map<BonusObj, Object> ret = new IdentityHashMap<>();
	for (final BonusContainer pobj : pc.getBonusContainerList())
	{
		// We exclude equipmods here as their bonuses are already counted in
		// the equipment they belong to.
		if (pobj != null && !(pobj instanceof EquipmentModifier))
		{
			boolean use = true;
			if (pobj instanceof PCClass)
			{
				// Class bonuses are only included if the level is greater
				// than 0
				// This is because 0 levels of a class can be added to
				// access spell casting etc
				use = pc.getLevel(((PCClass) pobj)) > 0;
			}
			if (use)
			{
				pobj.activateBonuses(pc);
				List<BonusObj> abs = pobj.getActiveBonuses(pc);
				for (BonusObj bo : abs)
				{
					ret.put(bo, pobj);
				}
			}
		}
	}

	if (pc.getUseTempMods())
	{
		ret.putAll(getTempBonuses());
	}
	return ret;
}
 
Example #22
Source Project: astor   Author: SpoonLabs   File: EdgesBuilder.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Simple constructor.
 * @param root tree root
 * @param tolerance below which points are consider to be identical
 */
public EdgesBuilder(final BSPTree<Sphere2D> root, final double tolerance) {
    this.root            = root;
    this.tolerance       = tolerance;
    this.edgeToNode      = new IdentityHashMap<Edge, BSPTree<Sphere2D>>();
    this.nodeToEdgesList = new IdentityHashMap<BSPTree<Sphere2D>, List<Edge>>();
}
 
Example #23
Source Project: dragonwell8_jdk   Author: alibaba   File: Capacity.java    License: GNU General Public License v2.0 5 votes vote down vote up
static int capacity(IdentityHashMap<?,?> map) {
    try {
        return ((Object[]) tableField.get(map)).length / 2;
    } catch (Throwable t) {
        throw new LinkageError("table", t);
    }
}
 
Example #24
Source Project: pcgen   Author: PCGen   File: BonusManager.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<BonusObj, TempBonusInfo> getFilteredTempBonusList()
{
	final Map<BonusObj, TempBonusInfo> ret = new IdentityHashMap<>();
	for (Map.Entry<BonusObj, TempBonusInfo> me : tempBonusBySource.entrySet())
	{
		BonusObj bonus = me.getKey();
		TempBonusInfo ti = me.getValue();
		if (!tempBonusFilters.contains(BonusDisplay.getBonusDisplayName(ti)))
		{
			ret.put(bonus, ti);
		}
	}
	return ret;
}
 
Example #25
Source Project: NewsMe   Author: iQuick   File: PostFormBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PostFormBuilder addHeader(String key, String val)
{
    if (this.headers == null)
    {
        headers = new IdentityHashMap<>();
    }
    headers.put(key, val);
    return this;
}
 
Example #26
Source Project: Telegram-FOSS   Author: Telegram-FOSS-Team   File: HlsMediaPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an HLS media period.
 *
 * @param extractorFactory An {@link HlsExtractorFactory} for {@link Extractor}s for the segments.
 * @param playlistTracker A tracker for HLS playlists.
 * @param dataSourceFactory An {@link HlsDataSourceFactory} for {@link DataSource}s for segments
 *     and keys.
 * @param mediaTransferListener The transfer listener to inform of any media data transfers. May
 *     be null if no listener is available.
 * @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
 * @param eventDispatcher A dispatcher to notify of events.
 * @param allocator An {@link Allocator} from which to obtain media buffer allocations.
 * @param compositeSequenceableLoaderFactory A factory to create composite {@link
 *     SequenceableLoader}s for when this media source loads data from multiple streams.
 * @param allowChunklessPreparation Whether chunkless preparation is allowed.
 * @param useSessionKeys Whether to use #EXT-X-SESSION-KEY tags.
 */
public HlsMediaPeriod(
    HlsExtractorFactory extractorFactory,
    HlsPlaylistTracker playlistTracker,
    HlsDataSourceFactory dataSourceFactory,
    @Nullable TransferListener mediaTransferListener,
    LoadErrorHandlingPolicy loadErrorHandlingPolicy,
    EventDispatcher eventDispatcher,
    Allocator allocator,
    CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    boolean allowChunklessPreparation,
    @HlsMetadataType int metadataType,
    boolean useSessionKeys) {
  this.extractorFactory = extractorFactory;
  this.playlistTracker = playlistTracker;
  this.dataSourceFactory = dataSourceFactory;
  this.mediaTransferListener = mediaTransferListener;
  this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
  this.eventDispatcher = eventDispatcher;
  this.allocator = allocator;
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.allowChunklessPreparation = allowChunklessPreparation;
  this.metadataType = metadataType;
  this.useSessionKeys = useSessionKeys;
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamWrapperIndices = new IdentityHashMap<>();
  timestampAdjusterProvider = new TimestampAdjusterProvider();
  sampleStreamWrappers = new HlsSampleStreamWrapper[0];
  enabledSampleStreamWrappers = new HlsSampleStreamWrapper[0];
  manifestUrlIndicesPerWrapper = new int[0][];
  eventDispatcher.mediaPeriodCreated();
}
 
Example #27
Source Project: gadtry   Author: harbby   File: OffHeapMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void putAllTest()
{
    final Map<String, Integer> offHeapMap = new OffHeapMap<>(
            (Integer str) -> String.valueOf(str).getBytes(UTF_8),
            (byte[] bytes) -> Integer.valueOf(new String(bytes, UTF_8)),
            IdentityHashMap::new
    );
    Map<String, Integer> integerMap = MutableMap.of("a1", 123);
    offHeapMap.putAll(integerMap);

    Assert.assertEquals(offHeapMap, integerMap);
}
 
Example #28
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: Capacity.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
Example #29
Source Project: kodkod   Author: emina   File: Translator.java    License: MIT License 5 votes vote down vote up
/**
 * Returns an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.  The annotated formula f will contain transitive source 
 * information for each of the subformulas of f.node.  Specifically, let t be a subformula of f.node, and
 * s be a descdendent of annotated.node from which t was derived.  Then, f.source[t] = annotated.source[s]. </p>
 * @requires simplified.keySet() in annotated.predicates()[RelationPredicate.NAME]
 * @requires no disj p, p': simplified.keySet() | simplified.get(p) = simplified.get(p') // this must hold in order
 * to maintain the invariant that each subformula of the returned formula has exactly one source
 * @requires for each p in simplified.keySet(), the formulas "p and [[this.bounds]]" and
 * "simplified.get(p) and [[this.bounds]]" are equisatisfiable
 * @return an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.
 */
private AnnotatedNode<Formula> inlinePredicates(final AnnotatedNode<Formula> annotated, final Map<RelationPredicate,Formula> simplified) {
	final Map<Node,Node> sources = new IdentityHashMap<Node,Node>();
	final AbstractReplacer inliner = new AbstractReplacer(annotated.sharedNodes()) {
		private RelationPredicate source =  null;			
		protected <N extends Node> N cache(N node, N replacement) {
			if (replacement instanceof Formula) {
				if (source==null) {
					final Node nsource = annotated.sourceOf(node);
					if (replacement!=nsource) 
						sources.put(replacement, nsource);
				} else {
					sources.put(replacement, source);
				}
			}
			return super.cache(node, replacement);
		}
		public Formula visit(RelationPredicate pred) {
			Formula ret = lookup(pred);
			if (ret!=null) return ret;
			source = pred;
			if (simplified.containsKey(pred)) {
				ret = simplified.get(pred).accept(this);
			} else {
				ret = pred.toConstraints().accept(this);
			}
			source = null;
			return cache(pred, ret);
		}
	};

	return annotate(annotated.node().accept(inliner), sources);
}
 
Example #30
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTRewriteAnalyzer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor for ASTRewriteAnalyzer.
 * <p>The given options cannot be null.</p>
 * 
 * @param content the content of the compilation unit to rewrite.
 * @param lineInfo line information for the content of the compilation unit to rewrite.
 * @param rootEdit the edit to add all generated edits to
 * @param eventStore the event store containing the description of changes
 * @param nodeInfos annotations to nodes, such as if a node is a string placeholder or a copy target
 * @param comments list of comments of the compilation unit to rewrite (elements of type <code>Comment</code>) or <code>null</code>.
 * @param options the current jdt.core options (formatting/compliance)
 * @param extendedSourceRangeComputer the source range computer to use
 * @param recoveryScannerData internal data used by {@link RecoveryScanner}
 */
public ASTRewriteAnalyzer(
		char[] content,
		LineInformation lineInfo,
		String lineDelim,
		TextEdit rootEdit,
		RewriteEventStore eventStore,
		NodeInfoStore nodeInfos,
		List comments,
		Map options,
		TargetSourceRangeComputer extendedSourceRangeComputer,
		RecoveryScannerData recoveryScannerData) {
	this.eventStore= eventStore;
	this.content= content;
	this.lineInfo= lineInfo;
	this.nodeInfos= nodeInfos;
	this.tokenScanner= null;
	this.currentEdit= rootEdit;
	this.sourceCopyInfoToEdit= new IdentityHashMap();
	this.sourceCopyEndNodes= new Stack();

	this.formatter= new ASTRewriteFormatter(nodeInfos, eventStore, options, lineDelim);

	this.extendedSourceRangeComputer = extendedSourceRangeComputer;
	this.lineCommentEndOffsets= new LineCommentEndOffsets(comments);
	
	this.options = options;
	
	this.recoveryScannerData = recoveryScannerData;
}