Java Code Examples for net.openhft.chronicle.values.Values#newHeapInstance()

The following examples show how to use net.openhft.chronicle.values.Values#newHeapInstance() . 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 File: DataKeyValueTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void dataKeyValueTest() {
    ChronicleMap<IntValue, LongValue> map =
            ChronicleMapBuilder.of(IntValue.class, LongValue.class)
                    .entries(1000).create();
    IntValue heapKey = Values.newHeapInstance(IntValue.class);
    LongValue heapValue = Values.newHeapInstance(LongValue.class);
    LongValue directValue = Values.newNativeReference(LongValue.class);

    heapKey.setValue(1);
    heapValue.setValue(1);
    map.put(heapKey, heapValue);
    assertEquals(1, map.get(heapKey).getValue());
    assertEquals(1, map.getUsing(heapKey, heapValue).getValue());

    heapKey.setValue(1);
    map.getUsing(heapKey, directValue).addValue(1);
    assertEquals(2, map.getUsing(heapKey, heapValue).getValue());

    heapKey.setValue(2);
    heapValue.setValue(3);
    map.put(heapKey, heapValue);
    assertEquals(3, map.get(heapKey).getValue());
}
 
Example 2
Source File: MemoryLeaksTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
private ChronicleMap<IntValue, String> getMap() throws IOException {
    VanillaChronicleMap<IntValue, String, ?> map;
    if (persisted) {
        map = (VanillaChronicleMap<IntValue, String, ?>)
                builder.createPersistedTo(folder.newFile());
    } else {
        map = (VanillaChronicleMap<IntValue, String, ?>) builder.create();
    }
    IntValue key = Values.newHeapInstance(IntValue.class);
    int i = 0;
    while (!map.hasExtraTierBulks()) {
        key.setValue(i++);
        map.put(key, "string" + i);
    }
    return map;
}
 
Example 3
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void testBytesMarshallable() throws IOException {
    ChronicleMapBuilder<IData, IData> builder = ChronicleMapBuilder
            .of(IData.class, IData.class)
            .entries(1000);
    try (ChronicleMap<IData, IData> map = newInstance(builder)) {
        for (int i = 0; i < 100; i++) {
            IData key = Values.newHeapInstance(IData.class);
            IData value = Values.newHeapInstance(IData.class);
            key.setText("key-" + i);
            key.setNumber(i);
            value.setNumber(i);
            value.setText("value-" + i);
            map.put(key, value);
            // check the map is still valid.
            map.entrySet().toString();
        }
    }
}
 
Example 4
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcquireUsingWithIntValueKeyStringBuilderValue() throws IOException {

    ChronicleMapBuilder<IntValue, StringBuilder> builder = ChronicleMapBuilder
            .of(IntValue.class, StringBuilder.class)
            .entries(1);

    try (ChronicleMap<IntValue, StringBuilder> map = newInstance(builder)) {

        IntValue key = Values.newHeapInstance(IntValue.class);
        key.setValue(1);

        StringBuilder using = new StringBuilder();

        try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key, using)) {
            using.append("Hello");
        }

        assertEquals("Hello", map.get(key).toString());
        mapChecks();
    }
}
 
Example 5
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testAcquireUsingImmutableUsing() throws IOException {

    ChronicleMapBuilder<IntValue, CharSequence> builder = ChronicleMapBuilder
            .of(IntValue.class, CharSequence.class)
            .entries(1);

    try (ChronicleMap<IntValue, CharSequence> map = newInstance(builder)) {

        IntValue using = Values.newHeapInstance(IntValue.class);
        using.setValue(1);

        try (Closeable c = map.acquireContext(using, "")) {
            assertTrue(using instanceof IntValue);
            using.setValue(1);
        }

        assertEquals(null, map.get("1"));
        mapChecks();
    }
}
 
Example 6
Source File: TrickyContextCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void nestedContextsSameKeyTest() {
    ChronicleMap<Integer, IntValue> map = ChronicleMapBuilder
            .of(Integer.class, IntValue.class)
            .entries(1).create();

    IntValue v = Values.newHeapInstance(IntValue.class);
    v.setValue(2);
    map.put(1, v);
    try (ExternalMapQueryContext<Integer, IntValue, ?> q = map.queryContext(1)) {
        q.writeLock().lock();
        // assume the value is 2
        IntValue v2 = q.entry().value().get();
        // this call should throw ISE, as accessing the key 1 in a nested context, but if not...
        map.remove(1);
        v.setValue(3);
        map.put(2, v);
        // prints 3
        System.out.println(v2.getValue());
    }
}
 
Example 7
Source File: SimpleMapOperationsListeningTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleLoggingTest() {
    ChronicleMap<Integer, IntValue> map = ChronicleMapBuilder
            .of(Integer.class, IntValue.class)
            .entries(100)
            .entryOperations(simpleLoggingMapEntryOperations())
            .defaultValueProvider(simpleLoggingDefaultValueProvider())
            .create();

    IntValue value = Values.newHeapInstance(IntValue.class);
    value.setValue(2);
    map.put(1, value);
    map.remove(1);
    map.acquireUsing(3, Values.newNativeReference(IntValue.class)).addAtomicValue(1);
    IntValue value2 = Values.newHeapInstance(IntValue.class);
    value2.setValue(5);
    map.forEachEntry(e -> e.context().replaceValue(e, e.context().wrapValueAsData(value2)));
    map.forEachEntry(e -> e.context().remove(e));

}
 
Example 8
Source File: ValueInterfaceWithEnumTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
/**
 * This test will throw an {@link ArrayIndexOutOfBoundsException}. This seems to occur only with Enums having even number of
 * values
 */
@Test
public void testValueInterface() {
    LongValue longValue = Values.newHeapInstance(LongValue.class);
    SimpleValueInterface simpleValueInterface = Values.newHeapInstance(SimpleValueInterface.class);

    ChronicleMap<LongValue, SimpleValueInterface> map = ChronicleMapBuilder.of(LongValue.class, SimpleValueInterface.class).entries(50).create();

    IntStream.range(1, 20).forEach(value -> {
        longValue.setValue(value);
        simpleValueInterface.setId(value);
        simpleValueInterface.setTruth(false);
        simpleValueInterface.setSVIEnum(SimpleValueInterface.SVIEnum.SIX);

        map.put(longValue, simpleValueInterface);
    });

    IntStream.range(1, 10).forEach(value -> {
        longValue.setValue(value);
        SimpleValueInterface simpleValueInterface1 = map.get(longValue);
        System.out.println(simpleValueInterface1.getId());
    });
}
 
Example 9
Source File: ChronicleMapUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenGetUsingQuery_whenCalled_shouldReturnResult() {
    LongValue key = Values.newHeapInstance(LongValue.class);
    StringBuilder country = new StringBuilder();
    key.setValue(1);
    persistedCountryMap.getUsing(key, country);
    assertThat(country.toString(), is(equalTo("Romania")));
    key.setValue(2);
    persistedCountryMap.getUsing(key, country);
    assertThat(country.toString(), is(equalTo("India")));
}
 
Example 10
Source File: LataTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    long startTime = 0;
    long endTime = 0;

    ChronicleMapBuilder<StringValue, IData> builder = ChronicleMapBuilder
            .of(StringValue.class, IData.class)
            .entries(max + 1000000);

    ChronicleMap<StringValue, IData> map = builder.create();
    StringValue[] keys = new StringValue[300];
    for (int i = 0; i < keys.length; i++) {
        keys[i] = Values.newHeapInstance(StringValue.class);
        keys[i].setValue("" + i);
    }
    IData value = Values.newHeapInstance(IData.class);
    IData dataValue = Values.newHeapInstance(IData.class);
    for (int index = 0; index < run; index++) {
        currentRun++;
        startTime = System.nanoTime();
        for (int i = 0; i < max; i++) {
            StringValue key = keys[i % keys.length];
            if (!(map.containsKey(key))) {
                value.setData(i);
                map.put(key, value);
            } else {
                value = map.acquireUsing(key, dataValue);
                value.addAtomicData(10);
            }
        }
        endTime = System.nanoTime();
        map.clear();
        System.out.println("Run" + currentRun + "Time taken"
                + (endTime - startTime));
    }
    map.close();
}
 
Example 11
Source File: ChronicleMapUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenGetQuery_whenCalled_shouldReturnResult() {
    LongValue key = Values.newHeapInstance(LongValue.class);
    key.setValue(1);
    CharSequence country = inMemoryCountryMap.get(key);
    assertThat(country.toString(), is(equalTo("Qatar")));
}
 
Example 12
Source File: OffHeapVarBitMetricStore.java    From yuvi with Apache License 2.0 5 votes vote down vote up
@Override
public List<Point> getSeries(long uuid) {
  final LongValue key = Values.newHeapInstance(LongValue.class);
  key.setValue(uuid);
  if (timeSeries.containsKey(key)) {
    ByteBuffer serializedValues = timeSeries.get(key);
    TimeSeriesIterator iterator = VarBitTimeSeries.deserialize(serializedValues);
    return iterator.getPoints();
  } else {
    return Collections.emptyList();
  }
}
 
Example 13
Source File: MemoryLeaksTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
private void tryCloseFromContext(ChronicleMap<IntValue, String> map) {
    // Test that the map could still be successfully closed and no leaks are introduced
    // by an attempt to close the map from within context.
    if (closeWithinContext) {
        IntValue key = Values.newHeapInstance(IntValue.class);
        try (ExternalMapQueryContext<IntValue, String, ?> c = map.queryContext(key)) {
            c.updateLock().lock();
            try {
                map.close();
            } catch (IllegalStateException expected) {
                // expected
            }
        }
    }
}
 
Example 14
Source File: OffHeapByteArrayExampleTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {

    // this objects will be reused
    ByteValue byteValue = Values.newHeapInstance(ByteValue.class);
    ByteArray value = Values.newHeapInstance(ByteArray.class);
    LongValue key = Values.newHeapInstance(LongValue.class);

    key.setValue(1);

    // this is kind of like byteValue[1] = 'b'
    byteValue.setValue((byte) EXPECTED);
    value.setByteValueAt(1, byteValue);

    chm.put(key, value);

    // clear the value to prove it works
    byteValue.setValue((byte) 0);
    value.setByteValueAt(1, byteValue);

    chm.getUsing(key, value);

    Assert.assertEquals(0, value.getByteValueAt(2).getValue());
    Assert.assertEquals(0, value.getByteValueAt(3).getValue());

    byte actual = value.getByteValueAt(1).getValue();
    Assert.assertEquals(EXPECTED, actual);

}
 
Example 15
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcquireUsingWithIntValueKey() throws IOException {

    ChronicleMapBuilder<IntValue, CharSequence> builder = ChronicleMapBuilder
            .of(IntValue.class, CharSequence.class)
            .entries(3);

    try (ChronicleMap<IntValue, CharSequence> map = newInstance(builder)) {

        IntValue key = Values.newHeapInstance(IntValue.class);
        key.setValue(1);

        CharSequence using = new StringBuilder();

        try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key, using)) {
            key.setValue(3);
            ((StringBuilder) using).append("Hello");
        }

        key.setValue(2);
        try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key, using)) {
            ((StringBuilder) using).append("World");
        }

        key.setValue(1);
        assertEquals("Hello", map.get(key).toString());
        mapChecks();
    }
}
 
Example 16
Source File: ChecksumEntryTest.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Test
public void testChecksumEntriesWithValueInterface() throws IOException {
    File file = Builder.getPersistenceFile();

    try (ChronicleMap<Integer, LongValue> map = ChronicleMap
            .of(Integer.class, LongValue.class)
            .entries(1)
            // Entry checksums make sense only for persisted Chronicle Maps, and are ON by
            // default for such maps
            .createPersistedTo(file)) {

        LongValue value = Values.newHeapInstance(LongValue.class);
        value.setValue(42);
        map.put(1, value);

        try (ExternalMapQueryContext<Integer, LongValue, ?> c = map.queryContext(1)) {
            // Update lock required for calling ChecksumEntry.checkSum()
            c.updateLock().lock();
            MapEntry<Integer, LongValue> entry = c.entry();
            Assert.assertNotNull(entry);
            ChecksumEntry checksumEntry = (ChecksumEntry) entry;
            Assert.assertTrue(checksumEntry.checkSum());

            // to access off-heap bytes, should call value().getUsing() with Native value
            // provided. Simple get() return Heap value by default
            LongValue nativeValue =
                    entry.value().getUsing(Values.newNativeReference(LongValue.class));
            // This value bytes update bypass Chronicle Map internals, so checksum is not
            // updated automatically
            nativeValue.setValue(43);
            Assert.assertFalse(checksumEntry.checkSum());

            // Restore correct checksum
            checksumEntry.updateChecksum();
            Assert.assertTrue(checksumEntry.checkSum());
        }
    }
}
 
Example 17
Source File: DemoChronicleMapTest.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Test
    public void testMap() throws IOException {
        File file = File.createTempFile("DummyOrders" + System.currentTimeMillis(), ".test");
        file.deleteOnExit();
        int maxEntries = 1000;
        try (ChronicleMap<IntValue, DemoOrderVOInterface> map = ChronicleMapBuilder
                .of(IntValue.class, DemoOrderVOInterface.class)
                .putReturnsNull(true)
                .removeReturnsNull(true)
                .entries(maxEntries)
                .entryAndValueOffsetAlignment(8)
                .createPersistedTo(file)) {
            IntValue key = Values.newHeapInstance(IntValue.class);

            DemoOrderVOInterface value = newNativeReference(DemoOrderVOInterface.class);
            DemoOrderVOInterface value2 = newNativeReference(DemoOrderVOInterface.class);

            // Initially populate the map
            for (int i = 0; i < maxEntries; i++) {
                key.setValue(i);

                map.acquireUsing(key, value);

                value.setSymbol("IBM-" + i);
                value.addAtomicOrderQty(1000);

                map.getUsing(key, value2);
                assertEquals("IBM-" + i, value.getSymbol().toString());
                assertEquals(1000, value.getOrderQty(), 0.0);
            }

            for (Map.Entry<IntValue, DemoOrderVOInterface> entry : map.entrySet()) {
                IntValue k = entry.getKey();
                DemoOrderVOInterface v = entry.getValue();

//                System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "<null>" : v.getSymbol()));
                assertNotNull(v);
            }
        }

        file.delete();
    }
 
Example 18
Source File: DemoChronicleMapTest.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Test
    public void testMapLocked() throws IOException {
        File file = File.createTempFile("DummyOrders-" + System.currentTimeMillis(), ".test");
        file.deleteOnExit();
        int maxEntries = 1000;
        try (ChronicleMap<IntValue, DemoOrderVOInterface> map = ChronicleMapBuilder
                .of(IntValue.class, DemoOrderVOInterface.class)
                .putReturnsNull(true)
                .removeReturnsNull(true)
                .entries(maxEntries)
                .entryAndValueOffsetAlignment(8)
                .createPersistedTo(file)) {
            IntValue key = Values.newHeapInstance(IntValue.class);

            DemoOrderVOInterface value = newNativeReference(DemoOrderVOInterface.class);
            DemoOrderVOInterface value2 = newNativeReference(DemoOrderVOInterface.class);

            // Initially populate the map
            for (int i = 0; i < maxEntries; i++) {
                key.setValue(i);

                try (net.openhft.chronicle.core.io.Closeable c =
                             map.acquireContext(key, value)) {
                    value.setSymbol("IBM-" + i);
                    value.addAtomicOrderQty(1000);
                }

                // TODO suspicious -- getUsing `value2`, working with `value` then
//                try (ReadContext rc = map.getUsingLocked(key, value2)) {
//                    assertTrue(rc.present());
//                    assertEquals("IBM-" + i, value.getSymbol());
//                    assertEquals(1000, value.getOrderQty(), 0.0);
//                }
            }

            for (Map.Entry<IntValue, DemoOrderVOInterface> entry : map.entrySet()) {
                IntValue k = entry.getKey();
                DemoOrderVOInterface v = entry.getValue();

//                System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "<null>" : v.getSymbol()));
                assertNotNull(v);
            }
        }
        file.delete();
    }
 
Example 19
Source File: RecoverTest.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Test
public void testCorruptedEntryRecovery() throws IOException {
    File file = getPersistenceFile();
    try (ChronicleMap<Integer, LongValue> map = ChronicleMap
            .of(Integer.class, LongValue.class)
            .entries(1)
            .createPersistedTo(file)) {

        LongValue value = Values.newHeapInstance(LongValue.class);
        value.setValue(42);
        map.put(1, value);

        try (ExternalMapQueryContext<Integer, LongValue, ?> c = map.queryContext(1)) {
            // Update lock required for calling ChecksumEntry.checkSum()
            c.updateLock().lock();
            MapEntry<Integer, LongValue> entry = c.entry();
            assertNotNull(entry);
            ChecksumEntry checksumEntry = (ChecksumEntry) entry;
            assertTrue(checksumEntry.checkSum());

            // to access off-heap bytes, should call value().getUsing() with Native value
            // provided. Simple get() return Heap value by default
            LongValue nativeValue =
                    entry.value().getUsing(Values.newNativeReference(LongValue.class));
            // This value bytes update bypass Chronicle Map internals, so checksum is not
            // updated automatically
            nativeValue.setValue(43);
            Assert.assertFalse(checksumEntry.checkSum());
        }
    }

    AtomicInteger corruptionCounter = new AtomicInteger(0);
    ChronicleHashCorruption.Listener corruptionListener =
            corruption -> corruptionCounter.incrementAndGet();
    //noinspection EmptyTryBlock
    try (ChronicleMap<Integer, LongValue> ignore = ChronicleMap
            .of(Integer.class, LongValue.class)
            .entries(1)
            .createOrRecoverPersistedTo(file, true, corruptionListener)) {
    }
    assertTrue(corruptionCounter.get() > 0);
}
 
Example 20
Source File: OffHeapVarBitMetricStore.java    From yuvi with Apache License 2.0 4 votes vote down vote up
public void addPoint(long uuid, ByteBuffer series) {
  LongValue key = Values.newHeapInstance(LongValue.class);
  key.setValue(uuid);
  timeSeries.put(key, series);
}