DefaultAttributeMap implements AttributeMap { @SuppressWarnings("unchecked") @Override public <T> Attribute<T> attr(AttributeKey<T> key) { if (key == null) { throw new NullPointerException("key"); } AtomicReferenceArray<DefaultAttribute<?>> attributes = this.attributes; if (attributes == null) { attributes = new AtomicReferenceArray<DefaultAttribute<?>>(BUCKET_SIZE); if (!updater.compareAndSet(this, null, attributes)) { attributes = this.attributes; } } int i = index(key); DefaultAttribute<?> head = attributes.get(i); if (head == null) { head = new DefaultAttribute(key); if (attributes.compareAndSet(i, null, head)) { return (Attribute<T>) head; } else { head = attributes.get(i); } } synchronized (head) { DefaultAttribute<?> curr = head; for (;;) { if (!curr.removed && curr.key == key) { return (Attribute<T>) curr; } DefaultAttribute<?> next = curr.next; if (next == null) { DefaultAttribute<T> attr = new DefaultAttribute<T>(head, key); curr.next = attr; attr.prev = curr; return attr; } else { curr = next; } } } }  @SuppressWarnings("unchecked") @Override Attribute<T> attr(AttributeKey<T> key); @Override boolean hasAttr(AttributeKey<T> key);  }
@Test public void testGetSetString() { AttributeKey<String> key = AttributeKey.valueOf("Nothing"); Attribute<String> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent("Whoohoo"); assertSame("Whoohoo", one.get()); one.setIfAbsent("What"); assertNotSame("What", one.get()); one.remove(); assertNull(one.get()); }
@Test public void testGetSetInt() { AttributeKey<Integer> key = AttributeKey.valueOf("Nada"); Attribute<Integer> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent(3653); assertEquals(one.get(), Integer.valueOf(3653)); one.setIfAbsent(1); assertNotSame(1, one.get()); one.remove(); assertNull(one.get()); }
@Test public void testSetRemove() { AttributeKey<Integer> key = AttributeKey.valueOf("key"); Attribute<Integer> attr = map.attr(key); attr.set(1); assertSame(1, attr.getAndRemove()); Attribute<Integer> attr2 = map.attr(key); attr2.set(2); assertSame(2, attr2.get()); assertNotSame(attr, attr2); }
@Test public void testGetAndSetWithNull() { AttributeKey<Integer> key = AttributeKey.valueOf("key"); Attribute<Integer> attr = map.attr(key); attr.set(1); assertSame(1, attr.getAndSet(null)); Attribute<Integer> attr2 = map.attr(key); attr2.set(2); assertSame(2, attr2.get()); assertSame(attr, attr2); }