Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
800
{ @Override public Lock doWork( Void state ) { try ( Transaction tx = db.beginTx() ) { return tx.acquireWriteLock( resource ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NestedTransactionLocksIT.java
801
public class NestedTransactionLocksIT { private GraphDatabaseService db; @Before public void before() throws Exception { db = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @After public void after() throws Exception { db.shutdown(); } private WorkerCommand<Void, Lock> acquireWriteLock( final Node resource ) { return new WorkerCommand<Void, Lock>() { @Override public Lock doWork( Void state ) { try ( Transaction tx = db.beginTx() ) { return tx.acquireWriteLock( resource ); } } }; } @Test public void nestedTransactionCanAcquireLocksFromTransactionObject() throws Exception { // given Node resource = createNode(); try ( Transaction outerTx = db.beginTx(); Transaction nestedTx = db.beginTx() ) { assertNotSame( outerTx, nestedTx ); try ( OtherThreadExecutor<Void> otherThread = new OtherThreadExecutor<>( "other thread", null ) ) { // when Lock lock = nestedTx.acquireWriteLock( resource ); Future<Lock> future = tryToAcquireSameLockOnAnotherThread( resource, otherThread ); // then acquireOnOtherThreadTimesOut( future ); // and when lock.release(); //then assertNotNull( future.get() ); } } } private void acquireOnOtherThreadTimesOut( Future<Lock> future ) throws InterruptedException, ExecutionException { try { future.get( 1, SECONDS ); fail( "The nested transaction seems to not have acquired the lock" ); } catch ( TimeoutException e ) { // Good } } private Future<Lock> tryToAcquireSameLockOnAnotherThread( Node resource, OtherThreadExecutor<Void> otherThread ) throws TimeoutException { Future<Lock> future = otherThread.executeDontWait( acquireWriteLock( resource ) ); otherThread.waitUntilWaiting(); return future; } private Node createNode() { try(Transaction tx = db.beginTx()) { Node n = db.createNode(); tx.success(); return n; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NestedTransactionLocksIT.java
802
private static class WorkerState { protected final GraphDatabaseService db; protected Transaction tx; WorkerState( GraphDatabaseService db ) { this.db = db; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ManyPropertyKeysIT.java
803
private static class FinishTx implements WorkerCommand<WorkerState, Void> { @Override public Void doWork( WorkerState state ) { state.tx.success(); //noinspection deprecation state.tx.finish(); return null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ManyPropertyKeysIT.java
804
private static class CreateNodeAndSetProperty implements WorkerCommand<WorkerState, Void> { private final String key; public CreateNodeAndSetProperty( String key ) { this.key = key; } @Override public Void doWork( WorkerState state ) { Node node = state.db.createNode(); node.setProperty( key, true ); return null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ManyPropertyKeysIT.java
805
private static class BeginTx implements WorkerCommand<WorkerState, Void> { @Override public Void doWork( WorkerState state ) { state.tx = state.db.beginTx(); return null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ManyPropertyKeysIT.java
806
public class ManyPropertyKeysIT { @Test public void creating_many_property_keys_should_have_all_loaded_the_next_restart() throws Exception { // GIVEN GraphDatabaseAPI db = databaseWithManyPropertyKeys( 3000 ); // The previous limit to load was 2500, so go some above that int countBefore = propertyKeyCount( db ); // WHEN db.shutdown(); db = database(); createNodeWithProperty( db, key( 2800 ), true ); // THEN assertEquals( countBefore, propertyKeyCount( db ) ); db.shutdown(); } @Test public void concurrently_creating_same_property_key_in_different_transactions_should_end_up_with_same_key_id() throws Exception { // GIVEN GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase(); OtherThreadExecutor<WorkerState> worker1 = new OtherThreadExecutor<>( "w1", new WorkerState( db ) ); OtherThreadExecutor<WorkerState> worker2 = new OtherThreadExecutor<>( "w2", new WorkerState( db ) ); worker1.execute( new BeginTx() ); worker2.execute( new BeginTx() ); // WHEN String key = "mykey"; worker1.execute( new CreateNodeAndSetProperty( key ) ); worker2.execute( new CreateNodeAndSetProperty( key ) ); worker1.execute( new FinishTx() ); worker2.execute( new FinishTx() ); worker1.close(); worker2.close(); // THEN assertEquals( 1, propertyKeyCount( db ) ); db.shutdown(); } private final File storeDir = TargetDirectory.forTest( getClass() ).makeGraphDbDir(); private GraphDatabaseAPI database() { return (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() ); } private GraphDatabaseAPI databaseWithManyPropertyKeys( int propertyKeyCount ) { GraphDatabaseAPI db = database(); try ( Transaction tx = db.beginTx() ) { Node node = db.createNode(); for ( int i = 0; i < propertyKeyCount; i++ ) node.setProperty( key( i ), true ); tx.success(); return db; } } private String key( int i ) { return "key" + i; } private Node createNodeWithProperty( GraphDatabaseService db, String key, Object value ) { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode(); node.setProperty( key, value ); tx.success(); return node; } } private int propertyKeyCount( GraphDatabaseAPI db ) { return (int) db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource().getNeoStore().getPropertyStore().getPropertyKeyTokenStore().getHighId(); } private static class WorkerState { protected final GraphDatabaseService db; protected Transaction tx; WorkerState( GraphDatabaseService db ) { this.db = db; } } private static class BeginTx implements WorkerCommand<WorkerState, Void> { @Override public Void doWork( WorkerState state ) { state.tx = state.db.beginTx(); return null; } } private static class CreateNodeAndSetProperty implements WorkerCommand<WorkerState, Void> { private final String key; public CreateNodeAndSetProperty( String key ) { this.key = key; } @Override public Void doWork( WorkerState state ) { Node node = state.db.createNode(); node.setProperty( key, true ); return null; } } private static class FinishTx implements WorkerCommand<WorkerState, Void> { @Override public Void doWork( WorkerState state ) { state.tx.success(); //noinspection deprecation state.tx.finish(); return null; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ManyPropertyKeysIT.java
807
static class DummyLoggerFactory implements ILoggerFactory { @Override public Logger getLogger( String name ) { return null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_LoggerFactoryIT.java
808
@RunWith(PowerMockRunner.class) @PrepareForTest(StaticLoggerBinder.class) public class LoggerFactoryIT { private TemporaryFolder graphDbFolder = new TemporaryFolder(); @Before public void setupTempFolder() throws IOException { graphDbFolder.create(); } @After public void cleanupTempFolder() { graphDbFolder.delete(); } @Test public void shouldFallbackToClassicLoggingServiceIfCustomStaticLoggerBinder() throws Exception { StaticLoggerBinder mockedInstance = PowerMockito.spy( StaticLoggerBinder.getSingleton() ); PowerMockito.when( mockedInstance.getLoggerFactory() ).thenReturn( new DummyLoggerFactory() ); PowerMockito.mockStatic( StaticLoggerBinder.class ); PowerMockito.when( StaticLoggerBinder.getSingleton() ).thenReturn( mockedInstance ); GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase( graphDbFolder .getRoot().getAbsolutePath() ); assertGraphDatabaseLoggingMatches( "org.neo4j.kernel.logging.ClassicLoggingService", graphDatabaseService ); } @Test public void shouldUseLogbackServiceWithStandardStaticLoggerBinder() throws Exception { GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase( graphDbFolder .getRoot().getAbsolutePath() ); assertGraphDatabaseLoggingMatches( "org.neo4j.kernel.logging.LogbackService", graphDatabaseService ); } /** * helper class to be return upon {@link org.slf4j.impl.StaticLoggerBinder#getLoggerFactory()} in a mocked * environment */ static class DummyLoggerFactory implements ILoggerFactory { @Override public Logger getLogger( String name ) { return null; } } private void assertGraphDatabaseLoggingMatches( String expectedLoggingClassname, Object graphDatabaseService ) { assertThat( graphDatabaseService, notNullValue() ); Object logging = getFieldValueByReflection( graphDatabaseService, "logging" ); assertThat( logging, notNullValue() ); assertThat( "gds.logging is not a " + expectedLoggingClassname + " instance", logging.getClass().getName(), is( expectedLoggingClassname ) ); } private Object getFieldValueByReflection( Object instance, String fieldName ) { Field field = findFieldRecursively( instance.getClass(), fieldName ); if ( field == null ) { throw new IllegalArgumentException( "found no field '" + fieldName + "' in class " + instance.getClass() + " or its superclasses." ); } else { try { field.setAccessible( true ); return field.get( instance ); } catch ( IllegalAccessException e ) { throw new RuntimeException( e ); } } } private Field findFieldRecursively( Class<? extends Object> clazz, String fieldName ) { try { return clazz.getDeclaredField( fieldName ); } catch ( NoSuchFieldException e ) { return findFieldRecursively( clazz.getSuperclass(), fieldName ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_LoggerFactoryIT.java
809
public class LockElement implements Lock { private Object resource; private final LockType lockType; private final LockManager lockManager; private final Transaction tx; public LockElement( Object resource, Transaction tx, LockType type, LockManager lockManager ) { if ( resource == null ) throw new IllegalArgumentException( "Null resource" ); if ( tx == null ) throw new IllegalArgumentException( "Null tx" ); this.tx = tx; this.resource = resource; this.lockType = type; this.lockManager = lockManager; } private boolean released() { return resource == null; } public boolean releaseIfAcquired() { if ( released() ) return false; lockType.release( lockManager, resource, tx ); resource = null; return true; } @Override public void release() { if ( !releaseIfAcquired() ) { throw new IllegalStateException( "Already released" ); } } @Override public String toString() { StringBuilder string = new StringBuilder( lockType.name() ).append( "-LockElement[" ); if ( released() ) string.append( "released," ); string.append( resource ); return string.append( ']' ).toString(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_LockElement.java
810
public class LargePropertiesIT extends AbstractNeo4jTestCase { private Node node; @Before public void createInitialNode() { node = getGraphDb().createNode(); } @After public void deleteInitialNode() { node.delete(); } @Test public void testLargeProperties() { byte[] bytes = new byte[10*1024*1024]; node.setProperty( "large_array", bytes ); node.setProperty( "large_string", new String( bytes ) ); newTransaction(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_LargePropertiesIT.java
811
public class LabelTokenHolder extends TokenHolder<Token> { public LabelTokenHolder( AbstractTransactionManager transactionManager, PersistenceManager persistenceManager, EntityIdGenerator idGenerator, TokenCreator tokenCreator ) { super( transactionManager, persistenceManager, idGenerator, tokenCreator ); } @Override protected Token newToken( String name, int id ) { return new Token( name, id ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_LabelTokenHolder.java
812
{ @Override public void run() { kernelEventHandlers.kernelPanic( error, cause ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_KernelPanicEventGenerator.java
813
public class KernelPanicEventGenerator { private final KernelEventHandlers kernelEventHandlers; public KernelPanicEventGenerator( KernelEventHandlers kernelEventHandlers ) { this.kernelEventHandlers = kernelEventHandlers; } public void generateEvent( final ErrorState error, final Throwable cause ) { ExecutorService executor = Executors.newSingleThreadExecutor( ); executor.execute( new Runnable() { @Override public void run() { kernelEventHandlers.kernelPanic( error, cause ); } } ); executor.shutdown(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_KernelPanicEventGenerator.java
814
private class JumpingIdGenerator implements IdGenerator { private final AtomicLong nextId = new AtomicLong(); private int leftToNextJump = sizePerJump/2; private long highBits = 0; @Override public long nextId() { long result = tryNextId(); if ( --leftToNextJump == 0 ) { leftToNextJump = sizePerJump; nextId.set( (0xFFFFFFFFL | (highBits++ << 32)) - sizePerJump/2 + 1 ); } return result; } private long tryNextId() { long result = nextId.getAndIncrement(); if ( result == IdGeneratorImpl.INTEGER_MINUS_ONE ) { result = nextId.getAndIncrement(); leftToNextJump--; } return result; } @Override public IdRange nextIdBatch( int size ) { throw new UnsupportedOperationException(); } @Override public void setHighId( long id ) { nextId.set( id ); } @Override public long getHighId() { return nextId.get(); } @Override public void freeId( long id ) { } @Override public void close() { } @Override public long getNumberOfIdsInUse() { return nextId.get(); } @Override public long getDefragCount() { return 0; } @Override public void delete() { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_JumpingIdGeneratorFactory.java
815
public class JumpingIdGeneratorFactory implements IdGeneratorFactory { private final Map<IdType, IdGenerator> generators = new EnumMap<IdType, IdGenerator>( IdType.class ); private final IdGenerator forTheRest = new EphemeralIdGenerator( null ); private final int sizePerJump; public JumpingIdGeneratorFactory( int sizePerJump ) { this.sizePerJump = sizePerJump; } public IdGenerator open( FileSystemAbstraction fs, File fileName, int grabSize, IdType idType, long highId ) { return get( idType ); } public IdGenerator get( IdType idType ) { if ( idType == IdType.NODE || idType == IdType.RELATIONSHIP || idType == IdType.PROPERTY || idType == IdType.STRING_BLOCK || idType == IdType.ARRAY_BLOCK ) { IdGenerator generator = generators.get( idType ); if ( generator == null ) { generator = new JumpingIdGenerator(); generators.put( idType, generator ); } return generator; } return forTheRest; } public void create( FileSystemAbstraction fs, File fileName, long highId ) { } private class JumpingIdGenerator implements IdGenerator { private final AtomicLong nextId = new AtomicLong(); private int leftToNextJump = sizePerJump/2; private long highBits = 0; @Override public long nextId() { long result = tryNextId(); if ( --leftToNextJump == 0 ) { leftToNextJump = sizePerJump; nextId.set( (0xFFFFFFFFL | (highBits++ << 32)) - sizePerJump/2 + 1 ); } return result; } private long tryNextId() { long result = nextId.getAndIncrement(); if ( result == IdGeneratorImpl.INTEGER_MINUS_ONE ) { result = nextId.getAndIncrement(); leftToNextJump--; } return result; } @Override public IdRange nextIdBatch( int size ) { throw new UnsupportedOperationException(); } @Override public void setHighId( long id ) { nextId.set( id ); } @Override public long getHighId() { return nextId.get(); } @Override public void freeId( long id ) { } @Override public void close() { } @Override public long getNumberOfIdsInUse() { return nextId.get(); } @Override public long getDefragCount() { return 0; } @Override public void delete() { } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_JumpingIdGeneratorFactory.java
816
public class AutoconfTest { @Before public void given() { this.db = (ImpermanentGraphDatabase)new TestGraphDatabaseFactory().newImpermanentDatabase(); } @Test public void shouldConfigureDatabaseMemoryMappingAutomatically() throws Exception { // when Config config = db.getConfig(); // then assertMemoryMappingAutoConfigured( config, "relationshipstore.db" ); assertMemoryMappingAutoConfigured( config, "nodestore.db" ); assertMemoryMappingAutoConfigured( config, "propertystore.db" ); assertMemoryMappingAutoConfigured( config, "propertystore.db.strings" ); assertMemoryMappingAutoConfigured( config, "propertystore.db.arrays" ); } private ImpermanentGraphDatabase db; @After public void stopDb() { try { if ( db != null ) { db.shutdown(); } } finally { db = null; } } private void assertMemoryMappingAutoConfigured( Config config, String store ) { Long configuredValue = config.get( memoryMappingSetting( "neostore." + store ) ); assertTrue( format( "Memory mapping for '%s' should be greater than 0, was %s", store, configuredValue ), configuredValue > 0 ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_AutoconfTest.java
817
{ @Override @SuppressWarnings("UnnecessaryUnboxing") public int compare( Object o1, Object o2 ) { return ((Property)o1).propertyKeyId() - ((Integer) o2).intValue(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_ArrayBasedPrimitive.java
818
{ @Override public void run() { for ( @SuppressWarnings("unused")String key : root.getPropertyKeys() ) precondition.set( true ); offenderSetUp.countDown(); root.setProperty( "tx", "offender" ); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestRaceOnMultipleNodeImpl.java
819
private static class ClockCacheTest<K, E> extends ClockCache<K, E> { private E cleanedElement = null; ClockCacheTest( String name, int maxSize ) { super( name, maxSize ); } @Override public void elementCleaned( E element ) { cleanedElement = element; } E getLastCleanedElement() { return cleanedElement; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestClockCache.java
820
public static class Entity implements EntityWithSizeObject { private int registeredSize; private final long id; Entity( long id ) { this.id = id; } @Override public int sizeOfObjectInBytesIncludingOverhead() { return 0; } @Override public long getId() { return id; } @Override public void setRegisteredSize( int size ) { registeredSize = size; } @Override public int getRegisteredSize() { return registeredSize; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestCacheTypes.java
821
public class TestCacheTypes { @Test public void softCacheShouldHonorPutSemantics() throws Exception { assertCacheHonorsPutsSemantics( new SoftLruCache<>( "test" ) ); } @Test public void weakCacheShouldHonorPutSemantics() throws Exception { assertCacheHonorsPutsSemantics( new WeakLruCache<>( "test" ) ); } @Test public void strongCacheShouldHonorPutSemantics() throws Exception { assertCacheHonorsPutsSemantics( new StrongReferenceCache<>( "test" ) ); } private void assertCacheHonorsPutsSemantics( Cache<EntityWithSizeObject> cache ) { Entity version1 = new Entity( 10 ); assertTrue( version1 == cache.put( version1 ) ); // WHEN Entity version2 = new Entity( 10 ); // THEN assertTrue( version1 == cache.put( version2 ) ); } public static class Entity implements EntityWithSizeObject { private int registeredSize; private final long id; Entity( long id ) { this.id = id; } @Override public int sizeOfObjectInBytesIncludingOverhead() { return 0; } @Override public long getId() { return id; } @Override public void setRegisteredSize( int size ) { registeredSize = size; } @Override public int getRegisteredSize() { return registeredSize; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestCacheTypes.java
822
@Ignore( "Impermanent graph database doesn't use High-Performance Cache" ) public class TestCacheObjectReuse { @Test public void highPerformanceCachesCanBeReusedBetweenSessions() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .setConfig( GraphDatabaseSettings.cache_type, HighPerformanceCacheProvider.NAME ).newGraphDatabase(); Cache<?> firstCache = first( nodeManager( db ).caches() ); db.shutdown(); db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .setConfig( GraphDatabaseSettings.cache_type, HighPerformanceCacheProvider.NAME ).newGraphDatabase(); try { Cache<?> secondCache = first( nodeManager( db ).caches() ); assertEquals( firstCache, secondCache ); } finally { db.shutdown(); } } private NodeManager nodeManager( GraphDatabaseAPI db ) { return db.getDependencyResolver().resolveDependency( NodeManager.class ); } @Test public void highPerformanceCachesAreRecreatedBetweenSessionsIfConfigChanges() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .setConfig( GraphDatabaseSettings.cache_type, HighPerformanceCacheProvider.NAME ).newGraphDatabase(); Cache<?> firstCache = first( nodeManager( db ).caches() ); db.shutdown(); db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .setConfig( GraphDatabaseSettings.cache_type, HighPerformanceCacheProvider.NAME ) .setConfig( HighPerformanceCacheSettings.node_cache_array_fraction, "10" ) .newGraphDatabase(); try { Cache<?> secondCache = first( nodeManager( db ).caches() ); assertFalse( firstCache.equals( secondCache ) ); } finally { db.shutdown(); } } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestCacheObjectReuse.java
823
public class StrongReferenceCache<E extends EntityWithSizeObject> implements Cache<E> { private final ConcurrentHashMap<Long,E> cache = new ConcurrentHashMap<>(); private final String name; private final HitCounter counter = new HitCounter(); public StrongReferenceCache( String name ) { this.name = name; } @Override public void clear() { cache.clear(); } @Override public E get( long key ) { return counter.count( cache.get( key ) ); } @Override public String getName() { return name; } public int maxSize() { return Integer.MAX_VALUE; } @Override public E put( E value ) { E previous = cache.putIfAbsent( value.getId(), value ); return previous != null ? previous : value; } public void putAll( List<E> list ) { for ( E entity : list ) { cache.put( entity.getId(), entity ); } } @Override public E remove( long key ) { return cache.remove( key ); } @Override public long hitCount() { return counter.getHitsCount(); } @Override public long missCount() { return counter.getMissCount(); } @Override public long size() { return cache.size(); } @Override public void putAll( Collection<E> values ) { for ( E entity : values ) { cache.put( entity.getId(), entity ); } } @Override public void updateSize( E entity, int newSize ) { // do nothing } @Override public void printStatistics() { // do nothing } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_StrongReferenceCache.java
824
@Service.Implementation( CacheProvider.class ) public class StrongCacheProvider extends CacheProvider { public static final String NAME = "strong"; public StrongCacheProvider() { super( NAME, "strong reference cache" ); } @Override public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config, Monitors monitors ) { return new StrongReferenceCache<NodeImpl>( NODE_CACHE_NAME ); } @Override public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config, Monitors monitors ) { return new StrongReferenceCache<RelationshipImpl>( RELATIONSHIP_CACHE_NAME ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_StrongCacheProvider.java
825
{ @Override public <FK, FV> SoftValue<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { return new SoftValue<>( key, value, queue ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SoftValue.java
826
public class SoftValue<K,V> extends SoftReference<V> implements ReferenceWithKey<K,V> { public final K key; public static Factory SOFT_VALUE_FACTORY = new Factory() { @Override public <FK, FV> SoftValue<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { return new SoftValue<>( key, value, queue ); } }; public SoftValue( K key, V value, ReferenceQueue<? super V> queue ) { super( value, queue ); this.key = key; } public SoftValue( K key, V value ) { super( value ); this.key = key; } @Override public K key() { return key; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SoftValue.java
827
public class SoftReferenceQueue<K,V> extends ReferenceQueue<SoftValue> { public SoftReferenceQueue() { super(); } public SoftValue<K,V> safePoll() { return (SoftValue) poll(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SoftReferenceQueue.java
828
public class SoftLruCache<E extends EntityWithSizeObject> extends ReferenceCache<E> { public SoftLruCache( String name ) { super( name, SOFT_VALUE_FACTORY ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SoftLruCache.java
829
@Service.Implementation( CacheProvider.class ) public class SoftCacheProvider extends CacheProvider { public static final String NAME = "soft"; public SoftCacheProvider() { super( NAME, "soft reference cache" ); } @Override public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config, Monitors monitors ) { return new SoftLruCache<NodeImpl>( NODE_CACHE_NAME ); } @Override public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config, Monitors monitors ) { return new SoftLruCache<RelationshipImpl>( RELATIONSHIP_CACHE_NAME ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SoftCacheProvider.java
830
public class SizeOfs { public static final int REFERENCE_SIZE = 8; /** * The size of a {@link String} object including object overhead and all state. * Excluding the reference to the String. * @param value the String to calculate size for. * @return the size of a {@link String}. */ public static int sizeOf( String value ) { return withObjectOverhead( 4/*offset*/ + 4/*count*/ + 4/*hash*/ + REFERENCE_SIZE/*value[] ref*/ + withArrayOverhead( +value.length() * 2 )/*value[]*/ ); } public static int sizeOfObject( Object stringOrArray ) { return stringOrArray.getClass().isArray() ? sizeOfArray( stringOrArray ) : sizeOf( (String ) stringOrArray ); } /** * The size of an array including object overhead and all items w/ potentially their references if non-primitives. * Excluding the reference to the array. * @param value the array to calculate size for. * @return the size of an array. */ public static int sizeOfArray( Object value ) { assert value.getClass().isArray(); if ( value instanceof String[] ) { int size = 0; for ( String string : (String[]) value ) { size += withReference( sizeOf( string ) ); } return withArrayOverhead( size ); } int base; if ( value instanceof byte[] || value instanceof boolean[] ) { base = 1; } else if ( value instanceof short[] || value instanceof char[] ) { base = 2; } else if ( value instanceof int[] || value instanceof float[] ) { base = 4; } else if ( value instanceof long[] || value instanceof double[] ) { base = 8; } else if ( value instanceof Byte[] || value instanceof Boolean[] || value instanceof Short[] || value instanceof Character[] || value instanceof Integer[] || value instanceof Float[] || value instanceof Long[] || value instanceof Double[] ) { // worst case base = withObjectOverhead( REFERENCE_SIZE + 8/*value in the boxed Number*/ ); } else { throw new IllegalStateException( "Unkown type: " + value.getClass() + " [" + value + "]" ); } return withArrayOverhead( base * Array.getLength( value ) ); } public static int withObjectOverhead( int size ) { // worst case, avg is somewhere between 8-16 depending on heap size return 16 + size; } public static int withArrayOverhead( int size ) { // worst case, avg is somewhere between 12-24 depending on heap size return 24 + size; } public static int withArrayOverheadIncludingReferences( int size, int length ) { return withArrayOverhead( size + length*REFERENCE_SIZE ); } public static int withReference( int size ) { // The standard size of a reference to an object. return REFERENCE_SIZE + size; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_SizeOfs.java
831
public class ReferenceWithKeyQueue<K,V> extends ReferenceQueue<ReferenceWithKey<K, V>> { public ReferenceWithKeyQueue() { super(); } public ReferenceWithKey<K, V> safePoll() { return (ReferenceWithKey<K, V>) poll(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_ReferenceWithKeyQueue.java
832
static class SpyCreatingWeakValueFactory implements ReferenceWithKey.Factory { ArrayList<ReferenceWithKey> weakValues = new ArrayList<>(); private final ArrayList<Object> hardReferencesToStopGC = new ArrayList<>(); private final ReferenceWithKey.Factory refFactory; SpyCreatingWeakValueFactory( ReferenceWithKey.Factory referenceFactory ) { refFactory = referenceFactory; } @Override public <FK, FV> ReferenceWithKey<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { ReferenceWithKey<FK, FV> ref = Mockito.spy( refFactory.newReference( key, value, queue ) ); hardReferencesToStopGC.add( value ); weakValues.add( ref ); return ref; } public void clearAndQueueReferenceNo( int index ) { ReferenceWithKey val = weakValues.get( index ); val.clear(); val.enqueue(); } public void reset() { weakValues.clear(); hardReferencesToStopGC.clear(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_ReferenceCacheTest.java
833
{ int invocations = 0; @Override public Object answer( InvocationOnMock invocationOnMock ) throws Throwable { if(invocations++ == 0) { return originalEntity; } else { return null; } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_ReferenceCacheTest.java
834
@RunWith(Parameterized.class) public class ReferenceCacheTest { static class SpyCreatingWeakValueFactory implements ReferenceWithKey.Factory { ArrayList<ReferenceWithKey> weakValues = new ArrayList<>(); private final ArrayList<Object> hardReferencesToStopGC = new ArrayList<>(); private final ReferenceWithKey.Factory refFactory; SpyCreatingWeakValueFactory( ReferenceWithKey.Factory referenceFactory ) { refFactory = referenceFactory; } @Override public <FK, FV> ReferenceWithKey<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { ReferenceWithKey<FK, FV> ref = Mockito.spy( refFactory.newReference( key, value, queue ) ); hardReferencesToStopGC.add( value ); weakValues.add( ref ); return ref; } public void clearAndQueueReferenceNo( int index ) { ReferenceWithKey val = weakValues.get( index ); val.clear(); val.enqueue(); } public void reset() { weakValues.clear(); hardReferencesToStopGC.clear(); } } @Parameterized.Parameters public static Collection<Object[]> parameters() { return asList( new Object[][]{ {new SpyCreatingWeakValueFactory( WeakValue.WEAK_VALUE_FACTORY )}, {new SpyCreatingWeakValueFactory( SoftValue.SOFT_VALUE_FACTORY )} }); } private SpyCreatingWeakValueFactory spyFactory; public ReferenceCacheTest( SpyCreatingWeakValueFactory factory ) { this.spyFactory = factory; spyFactory.reset(); // Instance is shared across tests } @Test public void shouldHandleExistingCacheEntryBeingGarbageCollectedDuringPutIfAbsent() throws Exception { // Given ReferenceCache<TestCacheTypes.Entity> cache = new ReferenceCache<>( "MyCache!", spyFactory ); TestCacheTypes.Entity originalEntity = new TestCacheTypes.Entity( 0 ); cache.put( originalEntity ); // Clear the weak reference that the cache will have created (emulating GC doing this) spyFactory.clearAndQueueReferenceNo( 0 ); // When TestCacheTypes.Entity newEntity = new TestCacheTypes.Entity( 0 ); TestCacheTypes.Entity returnedEntity = cache.put( newEntity ); // Then assertEquals(newEntity, returnedEntity); assertEquals(newEntity, cache.get(0)); } @Test public void shouldHandleReferenceGarbageCollectedDuringGet() throws Exception { // Given ReferenceCache<TestCacheTypes.Entity> cache = new ReferenceCache<>( "MyCache!", spyFactory ); final TestCacheTypes.Entity originalEntity = new TestCacheTypes.Entity( 0 ); cache.put( originalEntity ); // Clear the weak reference that the cache will have created (emulating GC doing this) when( spyFactory.weakValues.get( 0 ).get() ).thenAnswer( entityFirstTimeNullAfterThat( originalEntity ) ); // When TestCacheTypes.Entity returnedEntity = cache.get( 0 ); // Then assertEquals(originalEntity, returnedEntity); } private Answer<Object> entityFirstTimeNullAfterThat( final TestCacheTypes.Entity originalEntity ) { return new Answer<Object>() { int invocations = 0; @Override public Object answer( InvocationOnMock invocationOnMock ) throws Throwable { if(invocations++ == 0) { return originalEntity; } else { return null; } } }; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_ReferenceCacheTest.java
835
public class ReferenceCache<E extends EntityWithSizeObject> implements Cache<E> { private final ConcurrentHashMap<Long,ReferenceWithKey<Long,E>> cache = new ConcurrentHashMap<>(); private final ReferenceWithKeyQueue<Long,E> refQueue = new ReferenceWithKeyQueue<>(); private final String name; private final HitCounter counter = new HitCounter(); private final ReferenceWithKey.Factory referenceFactory; ReferenceCache( String name, ReferenceWithKey.Factory referenceFactory ) { this.name = name; this.referenceFactory = referenceFactory; } @Override public E put( E value ) { Long key = value.getId(); ReferenceWithKey<Long,E> ref = referenceFactory.newReference( key, value, (ReferenceQueue) refQueue ); // The block below retries until successful. The reason it needs to retry is that we are racing against GC // collecting the weak reference, and need to account for that happening at any time. do { ReferenceWithKey<Long, E> previous = cache.putIfAbsent( key, ref ); if(previous != null) { E prevValue = previous.get(); if(prevValue == null) { pollClearedValues(); // Re-run the loop body, re-attempting to get-or-set the reference in the cache. continue; } return prevValue; } else { return value; } } while(true); } @Override public void putAll( Collection<E> entities ) { Map<Long,ReferenceWithKey<Long,E>> softMap = new HashMap<>( entities.size() * 2 ); for ( E entity : entities ) { Long key = entity.getId(); ReferenceWithKey<Long,E> ref = referenceFactory.newReference( key, entity, (ReferenceQueue) refQueue ); softMap.put( key, ref ); } cache.putAll( softMap ); pollClearedValues(); } @Override public E get( long key ) { ReferenceWithKey<Long, E> ref = cache.get( key ); if ( ref != null ) { E value = ref.get(); if ( value == null ) { cache.remove( key ); } return counter.count( value ); } return counter.count( null ); } @Override public E remove( long key ) { ReferenceWithKey<Long, E> ref = cache.remove( key ); if ( ref != null ) { return ref.get(); } return null; } @Override public long size() { return cache.size(); } @Override public void clear() { cache.clear(); } @Override public long hitCount() { return counter.getHitsCount(); } @Override public long missCount() { return counter.getMissCount(); } @Override public String getName() { return name; } @Override public void updateSize( E entity, int newSize ) { // do nothing } @Override public void printStatistics() { // do nothing } private void pollClearedValues() { ReferenceWithKey<Long,E> clearedValue = refQueue.safePoll(); while ( clearedValue != null ) { cache.remove( clearedValue.key() ); clearedValue = refQueue.safePoll(); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_ReferenceCache.java
836
@Service.Implementation( CacheProvider.class ) public class NoCacheProvider extends CacheProvider { public static final String NAME = "none"; public NoCacheProvider() { super( NAME, "no cache" ); } @Override public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config, Monitors monitors ) { return new NoCache<NodeImpl>( NODE_CACHE_NAME ); } @Override public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config, Monitors monitors ) { return new NoCache<RelationshipImpl>( RELATIONSHIP_CACHE_NAME ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_NoCacheProvider.java
837
public class NoCache<E extends EntityWithSizeObject> implements Cache<E> { private final String name; private static final AtomicLong MISSES = new AtomicLong( 0 ); public NoCache( String name ) { this.name = name; } @Override public E put( E value ) { return value; } @Override public void putAll( Collection<E> values ) { } @Override public E get( long key ) { MISSES.incrementAndGet(); return null; } @Override public E remove( long key ) { return null; } @Override public long hitCount() { return 0; } @Override public long missCount() { return 0; } @Override public long size() { return 0; } @Override public void clear() { } @Override public String getName() { return name; } @Override public void updateSize( E entity, int newSize ) { // do nothing } @Override public void printStatistics() { // do nothing } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_NoCache.java
838
public static class Configuration { public static final Setting<Long> gc_monitor_wait_time = setting( "gc_monitor_wait_time", DURATION, "100ms" ); public static final Setting<Long> gc_monitor_threshold = setting("gc_monitor_threshold", DURATION, "200ms" ); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_MonitorGc.java
839
public class TestClockCache { @Test public void testCreate() { try { new ClockCache<Object, Object>( "TestCache", 0 ); fail( "Illegal maxSize should throw exception" ); } catch ( IllegalArgumentException e ) { // good } ClockCache<Object, Object> cache = new ClockCache<Object, Object>( "TestCache", 70 ); try { cache.put( null, new Object() ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.put( new Object(), null ); fail( "Null element should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.get( null ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.remove( null ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } cache.put( new Object(), new Object() ); cache.clear(); } private static class ClockCacheTest<K, E> extends ClockCache<K, E> { private E cleanedElement = null; ClockCacheTest( String name, int maxSize ) { super( name, maxSize ); } @Override public void elementCleaned( E element ) { cleanedElement = element; } E getLastCleanedElement() { return cleanedElement; } } @Test public void testSimple() { ClockCacheTest<Integer, String> cache = new ClockCacheTest<Integer, String>( "TestCache", 3 ); Map<String, Integer> valueToKey = new HashMap<String, Integer>(); Map<Integer, String> keyToValue = new HashMap<Integer, String>(); String s1 = new String( "1" ); Integer key1 = new Integer( 1 ); valueToKey.put( s1, key1 ); keyToValue.put( key1, s1 ); String s2 = new String( "2" ); Integer key2 = new Integer( 2 ); valueToKey.put( s2, key2 ); keyToValue.put( key2, s2 ); String s3 = new String( "3" ); Integer key3 = new Integer( 3 ); valueToKey.put( s3, key3 ); keyToValue.put( key3, s3 ); String s4 = new String( "4" ); Integer key4 = new Integer( 4 ); valueToKey.put( s4, key4 ); keyToValue.put( key4, s4 ); String s5 = new String( "5" ); Integer key5 = new Integer( 5 ); valueToKey.put( s5, key5 ); keyToValue.put( key5, s5 ); List<Integer> cleanedElements = new LinkedList<Integer>(); List<Integer> existingElements = new LinkedList<Integer>(); cache.put( key1, s1 ); cache.put( key2, s2 ); cache.put( key3, s3 ); assertEquals( null, cache.getLastCleanedElement() ); String fromKey2 = cache.get( key2 ); assertEquals( s2, fromKey2 ); String fromKey1 = cache.get( key1 ); assertEquals( s1, fromKey1 ); String fromKey3 = cache.get( key3 ); assertEquals( s3, fromKey3 ); cache.put( key4, s4 ); assertFalse( s4.equals( cache.getLastCleanedElement() ) ); cleanedElements.add( valueToKey.get( cache.getLastCleanedElement() ) ); existingElements.remove( valueToKey.get( cache.getLastCleanedElement() ) ); cache.put( key5, s5 ); assertFalse( s4.equals( cache.getLastCleanedElement() ) ); assertFalse( s5.equals( cache.getLastCleanedElement() ) ); cleanedElements.add( valueToKey.get( cache.getLastCleanedElement() ) ); existingElements.remove( valueToKey.get( cache.getLastCleanedElement() ) ); int size = cache.size(); assertEquals( 3, size ); for ( Integer key : cleanedElements ) { assertEquals( null, cache.get( key ) ); } for ( Integer key : existingElements ) { assertEquals( keyToValue.get( key ), cache.get( key ) ); } cache.clear(); assertEquals( 0, cache.size() ); for ( Integer key : keyToValue.keySet() ) { assertEquals( null, cache.get( key ) ); } } @Test public void shouldUpdateSizeWhenRemoving() throws Exception { ClockCache<String, Integer> cache = new ClockCache<String, Integer>( "foo", 3 ); cache.put( "bar", 42 ); cache.put( "baz", 87 ); cache.remove( "bar" ); assertThat( cache.size(), is( 1 ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestClockCache.java
840
public class TestEnterpriseCacheType { @Test public void defaultEmbeddedGraphDbShouldUseHighPerformanceCache() throws Exception { // GIVEN // -- an embedded graph database with default cache type config db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); // THEN // -- the selected cache type should be HPC assertEquals( HighPerformanceCacheProvider.NAME, getCacheTypeUsed() ); } @Test public void defaultHaGraphDbShouldUseHighPerformanceCache() throws Exception { // GIVEN // -- an HA graph database with default cache type config db = (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory().newHighlyAvailableDatabaseBuilder( storeDir ) .setConfig( server_id, "1" ).setConfig( ClusterSettings.initial_hosts, ":5001" ).newGraphDatabase(); // THEN assertEquals( HighPerformanceCacheProvider.NAME, getCacheTypeUsed() ); } private String getCacheTypeUsed() { return db.getDependencyResolver().resolveDependency( Config.class ).get( GraphDatabaseSettings.cache_type ); } @After public void after() throws Exception { if ( db != null ) { db.shutdown(); } } private String storeDir = TargetDirectory.forTest( getClass() ).makeGraphDbDir().getAbsolutePath(); private GraphDatabaseAPI db; }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestEnterpriseCacheType.java
841
{ @Override public int compare( Property o1, Property o2 ) { return o1.propertyKeyId() - o2.propertyKeyId(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_ArrayBasedPrimitive.java
842
public class TestHighPerformanceCache { private HighPerformanceCache<Entity> cache; @Before public void setup() { cache = new HighPerformanceCache<>( new AtomicReferenceArray<Entity>( 10 ) ); } @Test public void assertThatPutPutsSomething() { long key = 5; Entity entity = new Entity( key, 10 ); cache.put( entity ); assertEquals( entity, cache.get( key ) ); } @Test public void assertThatRemoveRemovesSomething() { long key = 5; Entity entity = new Entity( key, 10 ); cache.put( entity ); assertEquals( entity, cache.get( key ) ); cache.remove( key ); assertEquals( null, cache.get( key ) ); } @Test public void assertThatPutKeepsCorrectSize() { cache = new HighPerformanceCache<Entity>( new AtomicReferenceArray<Entity>( 10 ) ) { @Override protected int getPosition( EntityWithSizeObject obj ) { // For this test case return the same position every time. return 1; } }; final int size = 10; SneakyEntity oldEntity = new SneakyEntity( 0l, size ) // with ID 0 { @Override void doThisBadStuffInSizeCall() { // when AAC.put asks the old object for size this will emulate a cache.updateSize( oldObj, size, size + 1 ) updateSize( size + 1 ); cache.updateSize( this, size + 1 ); } }; cache.put( oldEntity ); // will increase internal size to 11 and update cache oldEntity.updateSize( size ); // will reset entity size to 10 Entity newEntity = new Entity( 1l, 11 ); // with ID 1, but they get the same position due to the custom cache cache.put( newEntity ); // will increase oldEntity size + 1 when cache.put asks for it assertEquals( 11, cache.size() ); } @Test public void assertThatRemoveKeepsCorrectSize() { final int size = 10; SneakyEntity entity = new SneakyEntity( 0l, size ) { @Override void doThisBadStuffInSizeCall() { // when AAC.remove asks the object for size this will emulate a cache.updateSize( oldObj, size, size + 1 ) updateSize( size + 1 ); cache.updateSize( this, size + 1 ); } }; cache.put( entity ); // will increase internal size to 11 and update cache entity.updateSize( size ); // will reset entity size to 10 cache.remove( entity.getId() ); assertEquals( 0, cache.size() ); } @Test(expected = NullPointerException.class ) public void assertNullPutTriggersNPE() { cache.put( null ); } @Test(expected = IndexOutOfBoundsException.class ) public void assertPutCanHandleWrongId() { Entity entity = new Entity( -1l, 1 ); cache.put( entity ); } @Test(expected = IndexOutOfBoundsException.class ) public void assertGetCanHandleWrongId() { cache.get( -1l ); } @Test(expected = IndexOutOfBoundsException.class ) public void assertRemoveCanHandleWrongId() { cache.remove( -1l ); } @Test public void shouldReturnExistingObjectIfDifferentObjectButSameId() throws Exception { // GIVEN int id = 10; Entity version1 = new Entity( id, 0 ); assertTrue( version1 == cache.put( version1 ) ); // WHEN Entity version2 = new Entity( id, 0 ); // THEN assertTrue( version1 == cache.put( version2 ) ); } @Test public void shouldListenToPurges() throws Exception { // GIVEN Monitor monitor = mock( Monitor.class ); cache = new HighPerformanceCache<>( 100, 1.0f, SECONDS.toMillis( 10 ), "purge test", StringLogger.DEV_NULL, monitor ); cache.put( new Entity( 0, 10 ) ); cache.put( new Entity( 1, 50 ) ); cache.put( new Entity( 2, 10 ) ); cache.put( new Entity( 3, 10 ) ); verifyZeroInteractions( monitor ); // WHEN cache.put( new Entity( 4, 50 ) ); // THEN verify( monitor ).purged( 130L, 60L, 3 ); } private static class Entity implements EntityWithSizeObject { private final long id; private int size; private int registeredSize; Entity( long id, int size ) { this.id = id; this.size = size; } @Override public int sizeOfObjectInBytesIncludingOverhead() { return size; } @Override public long getId() { return id; } public void updateSize( int newSize ) { this.size = newSize; } @Override public void setRegisteredSize( int size ) { this.registeredSize = size; } @Override public int getRegisteredSize() { return registeredSize; } } private static abstract class SneakyEntity extends Entity { SneakyEntity( long id, int size ) { super( id, size ); } @Override public int sizeOfObjectInBytesIncludingOverhead() { int size = super.sizeOfObjectInBytesIncludingOverhead(); doThisBadStuffInSizeCall(); return size; } abstract void doThisBadStuffInSizeCall(); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
843
abstract class ArrayBasedPrimitive extends Primitive implements EntityWithSizeObject { private volatile DefinedProperty[] properties; private volatile int registeredSize; ArrayBasedPrimitive( boolean newPrimitive ) { super( newPrimitive ); } @Override public void setRegisteredSize( int size ) { this.registeredSize = size; } @Override public int getRegisteredSize() { return registeredSize; } @Override public int sizeOfObjectInBytesIncludingOverhead() { int size = REFERENCE_SIZE/*properties reference*/ + 8/*registered size*/; if ( properties != null && properties.length > 0 ) { size = withArrayOverheadIncludingReferences( size, properties.length ); // the actual properties[] object for ( DefinedProperty data : properties ) { size += data.sizeOfObjectInBytesIncludingOverhead(); } } return withObjectOverhead( size ); } @Override protected void setEmptyProperties() { properties = NO_PROPERTIES; } private DefinedProperty[] toPropertyArray( Collection<DefinedProperty> loadedProperties ) { if ( loadedProperties == null || loadedProperties.size() == 0 ) { return NO_PROPERTIES; } DefinedProperty[] result = new DefinedProperty[loadedProperties.size()]; int i = 0; for ( DefinedProperty property : loadedProperties ) { result[i++] = property; } sort( result ); return result; } private static void sort( Property[] array ) { Arrays.sort( array, PROPERTY_DATA_COMPARATOR_FOR_SORTING ); } private static final Comparator<Property> PROPERTY_DATA_COMPARATOR_FOR_SORTING = new Comparator<Property>() { @Override public int compare( Property o1, Property o2 ) { return o1.propertyKeyId() - o2.propertyKeyId(); } }; /* This is essentially a deliberate misuse of Comparator, knowing details about Arrays#binarySearch. * The signature is binarySearch( T[] array, T key, Comparator<T> ), but in this case we're * comparing PropertyData[] to an int as key. To avoid having to create a new object for * the key for each call we create a single Comparator taking the PropertyData as first * argument and the key as the second, as #binarySearch does internally. Although the int * here will be boxed I imagine it to be slightly better, with Integer caching for low * integers. */ @SuppressWarnings( "rawtypes" ) static final Comparator PROPERTY_DATA_COMPARATOR_FOR_BINARY_SEARCH = new Comparator() { @Override @SuppressWarnings("UnnecessaryUnboxing") public int compare( Object o1, Object o2 ) { return ((Property)o1).propertyKeyId() - ((Integer) o2).intValue(); } }; @Override protected boolean hasLoadedProperties() { return properties != null; } @Override protected Iterator<DefinedProperty> getCachedProperties() { return iterator( properties ); } @Override protected PrimitiveLongIterator getCachedPropertyKeys() { return new PrimitiveLongIterator() { private final Property[] localProperties = properties; private int i; @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return localProperties[i++].propertyKeyId(); } @Override public boolean hasNext() { return i < localProperties.length; } }; } @SuppressWarnings( "unchecked" ) @Override protected Property getCachedProperty( int key ) { Property[] localProperties = properties; int index = Arrays.binarySearch( localProperties, key, PROPERTY_DATA_COMPARATOR_FOR_BINARY_SEARCH ); return index < 0 ? noProperty( key ) : localProperties[index]; } protected abstract Property noProperty( int key ); @Override protected void setProperties( Iterator<DefinedProperty> properties ) { this.properties = toPropertyArray( asCollection( properties ) ); } @Override protected DefinedProperty getPropertyForIndex( int keyId ) { DefinedProperty[] localProperties = properties; int index = Arrays.binarySearch( localProperties, keyId, PROPERTY_DATA_COMPARATOR_FOR_BINARY_SEARCH ); return index < 0 ? null : localProperties[index]; } @Override protected void commitPropertyMaps( ArrayMap<Integer, DefinedProperty> cowPropertyAddMap, ArrayMap<Integer, DefinedProperty> cowPropertyRemoveMap, long firstProp ) { synchronized ( this ) { // Dereference the volatile once to avoid multiple barriers DefinedProperty[] newArray = properties; if ( newArray == null ) { return; } /* * add map will definitely be added in the properties array - all properties * added and later removed in the same tx are removed from there as well. * The remove map will not necessarily be removed, since it may hold a prop that was * added in this tx. So the difference in size is all the keys that are common * between properties and remove map subtracted by the add map size. */ int extraLength = 0; if (cowPropertyAddMap != null) { extraLength += cowPropertyAddMap.size(); } int newArraySize = newArray.length; // make sure that we don't make inplace modifications to the existing array // TODO: Refactor this to guarantee only one copy, // currently it can do two copies in the clone() case if it also compacts if ( extraLength > 0 ) { DefinedProperty[] oldArray = newArray; newArray = new DefinedProperty[oldArray.length + extraLength]; System.arraycopy( oldArray, 0, newArray, 0, oldArray.length ); } else { newArray = newArray.clone(); } if ( cowPropertyRemoveMap != null ) { for ( Integer keyIndex : cowPropertyRemoveMap.keySet() ) { for ( int i = 0; i < newArraySize; i++ ) { Property existingProperty = newArray[i]; if ( existingProperty.propertyKeyId() == keyIndex ) { int swapWith = --newArraySize; newArray[i] = newArray[swapWith]; newArray[swapWith] = null; break; } } } } if ( cowPropertyAddMap != null ) { for ( DefinedProperty addedProperty : cowPropertyAddMap.values() ) { for ( int i = 0; i < newArray.length; i++ ) { Property existingProperty = newArray[i]; if ( existingProperty == null || addedProperty.propertyKeyId() == existingProperty.propertyKeyId() ) { newArray[i] = Property.property( addedProperty.propertyKeyId(), addedProperty.value() ); if ( existingProperty == null ) { newArraySize++; } break; } } } } // these size changes are updated from lock releaser if ( newArraySize < newArray.length ) { DefinedProperty[] compactedNewArray = new DefinedProperty[newArraySize]; System.arraycopy( newArray, 0, compactedNewArray, 0, newArraySize ); sort( compactedNewArray ); properties = compactedNewArray; } else { sort( newArray ); properties = newArray; } } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_ArrayBasedPrimitive.java
844
{ @Override public <FK, FV> WeakValue<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { return new WeakValue<>( key, value, queue ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_WeakValue.java
845
public class WeakValue<K,V> extends WeakReference<V> implements ReferenceWithKey<K,V> { public final K key; public static Factory WEAK_VALUE_FACTORY = new Factory() { @Override public <FK, FV> WeakValue<FK, FV> newReference( FK key, FV value, ReferenceQueue<? super FV> queue ) { return new WeakValue<>( key, value, queue ); } }; private WeakValue( K key, V value, ReferenceQueue<? super V> queue ) { super( value, queue ); this.key = key; } private WeakValue( K key, V value ) { super( value ); this.key = key; } @Override public K key() { return key; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_WeakValue.java
846
public class WeakLruCache<E extends EntityWithSizeObject> extends ReferenceCache<E> { public WeakLruCache( String name ) { super( name, WEAK_VALUE_FACTORY ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_WeakLruCache.java
847
@Service.Implementation( CacheProvider.class ) public class WeakCacheProvider extends CacheProvider { public static final String NAME = "weak"; public WeakCacheProvider() { super( NAME, "weak reference cache" ); } @Override public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config, Monitors monitors ) { return new WeakLruCache<>( NODE_CACHE_NAME ); } @Override public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config, Monitors monitors ) { return new WeakLruCache<>( RELATIONSHIP_CACHE_NAME ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_WeakCacheProvider.java
848
private static class RelationshipsSize { private int length; private int size; RelationshipsSize add( RelationshipArraySize array ) { this.size += array.size(); this.length++; return this; } int size() { return withArrayOverheadIncludingReferences( size, length ); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestSizeOf.java
849
private static class RelationshipArraySize { private int nrOut; private int nrIn; private int nrLoop; RelationshipArraySize withOutRelationships( int nrOut ) { this.nrOut = nrOut; return this; } RelationshipArraySize withRelationshipInAllDirections( int nr ) { this.nrOut = this.nrIn = this.nrLoop = nr; return this; } int size() { int size = 8 + // for the type (padded) REFERENCE_SIZE * 2; // for the IdBlock references in RelIdArray for ( int rels : new int[] { nrOut, nrIn, nrLoop } ) { if ( rels > 0 ) { size += withObjectOverhead( withReference( withArrayOverhead( 4 * (rels + 1) ) ) ); } } if ( nrLoop > 0 ) { size += REFERENCE_SIZE; // RelIdArrayWithLoops is used for for those with loops in } return withObjectOverhead( size ); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestSizeOf.java
850
private static class PropertiesSize { private int length; private int size; /* * For each PropertyData, this will include the object overhead of the PropertyData object itself. */ private PropertiesSize add( int size ) { length++; this.size += withObjectOverhead( size ); return this; } PropertiesSize withSmallPrimitiveProperty() { return add( _8_BYTES_FOR_VALUE ); } PropertiesSize withStringProperty( String value ) { return add( withReference( sizeOf( value ) ) ); } PropertiesSize withArrayProperty( Object array ) { return add( withReference( sizeOfArray( array ) ) ); } public int size() { // array overhead here is the NodeImpl's properties[] itself return withArrayOverheadIncludingReferences( size, length ); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestSizeOf.java
851
public class TestSizeOf { private static GraphDatabaseAPI db; public static final int _8_BYTES_FOR_VALUE = 8; @BeforeClass public static void setupDB() { db = (GraphDatabaseAPI) new TestGraphDatabaseFactory(). newImpermanentDatabaseBuilder(). setConfig( GraphDatabaseSettings.cache_type, HighPerformanceCacheProvider.NAME ). newGraphDatabase(); } @AfterClass public static void shutdown() throws Exception { db.shutdown(); } @Before public void clearCache() { nodeManager().clearCache(); } @SuppressWarnings( "unchecked" ) private Cache<NodeImpl> getNodeCache() { // This is a bit fragile because we depend on the order of caches() returns its caches. return (Cache<NodeImpl>) IteratorUtil.first( nodeManager().caches() ); } private NodeManager nodeManager() { return db.getDependencyResolver().resolveDependency( NodeManager.class ); } private Node createNodeAndLoadFresh( Map<String, Object> properties, int nrOfRelationships, int nrOfTypes ) { return createNodeAndLoadFresh( properties, nrOfRelationships, nrOfTypes, 0 ); } private Node createNodeAndLoadFresh( Map<String, Object> properties, int nrOfRelationships, int nrOfTypes, int directionStride ) { Node node = null; Transaction tx = db.beginTx(); try { node = db.createNode(); setProperties( properties, node ); for ( int t = 0; t < nrOfTypes; t++ ) { RelationshipType type = DynamicRelationshipType.withName( relTypeName( t ) ); for ( int i = 0, dir = 0; i < nrOfRelationships; i++, dir = (dir+directionStride)%3 ) { switch ( dir ) { case 0: node.createRelationshipTo( db.createNode(), type ); break; case 1: db.createNode().createRelationshipTo( node, type ); break; case 2: node.createRelationshipTo( node, type ); break; default: throw new IllegalArgumentException( "Invalid direction " + dir ); } } } tx.success(); } finally { tx.finish(); } clearCache(); if ( !properties.isEmpty() ) { loadProperties( node ); } if ( nrOfRelationships*nrOfTypes > 0 ) { countRelationships( node ); } return node; } private void countRelationships( Node node ) { Transaction transaction = db.beginTx(); try { count( node.getRelationships() ); } finally { transaction.finish(); } } private void loadProperties( PropertyContainer entity ) { Transaction transaction = db.beginTx(); try { for ( String key : entity.getPropertyKeys() ) { entity.getProperty( key ); } } finally { transaction.finish(); } } private void setProperties( Map<String, Object> properties, PropertyContainer entity ) { for ( Map.Entry<String, Object> property : properties.entrySet() ) { entity.setProperty( property.getKey(), property.getValue() ); } } private Relationship createRelationshipAndLoadFresh( Map<String, Object> properties ) { Relationship relationship = null; Transaction tx = db.beginTx(); try { relationship = db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST ); setProperties( properties, relationship ); tx.success(); } finally { tx.finish(); } clearCache(); if ( !properties.isEmpty() ) { loadProperties( relationship ); } return relationship; } private String relTypeName( int t ) { return "mytype" + t; } @Test public void cacheSizeCorrelatesWithNodeSizeAfterFullyLoadingRelationships() throws Exception { // Create node with a couple of relationships Node node = createNodeAndLoadFresh( map(), 10, 1 ); Cache<NodeImpl> nodeCache = getNodeCache(); // Just an initial sanity assertion, we start off with a clean cache clearCache(); assertEquals( 0, nodeCache.size() ); // Fully cache the node and its relationships countRelationships( node ); // Now the node cache size should be the same as doing node.size() assertEquals( nodeManager().getNodeForProxy( node.getId(), null ).sizeOfObjectInBytesIncludingOverhead(), nodeCache.size() ); } private int sizeOfNode( Node node ) { try(Transaction ignore = db.beginTx()) { return nodeManager().getNodeForProxy( node.getId(), null ).sizeOfObjectInBytesIncludingOverhead(); } } private int sizeOfRelationship( Relationship relationship ) { try(Transaction ignore = db.beginTx()) { return nodeManager().getRelationshipForProxy( relationship.getId() ) .sizeOfObjectInBytesIncludingOverhead(); } } private int withNodeOverhead( int size ) { return withObjectOverhead( REFERENCE_SIZE/*properties reference*/+ 8/*registeredSize w/ padding*/+ REFERENCE_SIZE/*relationships reference*/+ 8/*relChainPosition*/+ 8/*id*/+ 8/*labels[] reference*/+ size ); } private int withRelationshipOverhead( int size ) { return withObjectOverhead( REFERENCE_SIZE/*properties reference*/+ 8/*registeredSize w/ padding*/+ 8/*idAndMore*/+ 8/*startNodeId and endNodeId*/+ size ); } public static RelationshipArraySize array() { return new RelationshipArraySize(); } private static class RelationshipArraySize { private int nrOut; private int nrIn; private int nrLoop; RelationshipArraySize withOutRelationships( int nrOut ) { this.nrOut = nrOut; return this; } RelationshipArraySize withRelationshipInAllDirections( int nr ) { this.nrOut = this.nrIn = this.nrLoop = nr; return this; } int size() { int size = 8 + // for the type (padded) REFERENCE_SIZE * 2; // for the IdBlock references in RelIdArray for ( int rels : new int[] { nrOut, nrIn, nrLoop } ) { if ( rels > 0 ) { size += withObjectOverhead( withReference( withArrayOverhead( 4 * (rels + 1) ) ) ); } } if ( nrLoop > 0 ) { size += REFERENCE_SIZE; // RelIdArrayWithLoops is used for for those with loops in } return withObjectOverhead( size ); } } static RelationshipsSize relationships() { return new RelationshipsSize(); } private static class RelationshipsSize { private int length; private int size; RelationshipsSize add( RelationshipArraySize array ) { this.size += array.size(); this.length++; return this; } int size() { return withArrayOverheadIncludingReferences( size, length ); } } static PropertiesSize properties() { return new PropertiesSize(); } private static class PropertiesSize { private int length; private int size; /* * For each PropertyData, this will include the object overhead of the PropertyData object itself. */ private PropertiesSize add( int size ) { length++; this.size += withObjectOverhead( size ); return this; } PropertiesSize withSmallPrimitiveProperty() { return add( _8_BYTES_FOR_VALUE ); } PropertiesSize withStringProperty( String value ) { return add( withReference( sizeOf( value ) ) ); } PropertiesSize withArrayProperty( Object array ) { return add( withReference( sizeOfArray( array ) ) ); } public int size() { // array overhead here is the NodeImpl's properties[] itself return withArrayOverheadIncludingReferences( size, length ); } } private void assertArraySize( Object array, int sizePerItem ) { assertEquals( withArrayOverhead( Array.getLength( array )*sizePerItem ), sizeOfArray( array ) ); } @Test public void sizeOfEmptyNode() throws Exception { Node node = createNodeAndLoadFresh( map(), 0, 0 ); assertEquals( withNodeOverhead( 0 ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithOneProperty() throws Exception { Node node = createNodeAndLoadFresh( map( "age", 5 ), 0, 0 ); assertEquals( withNodeOverhead( properties().withSmallPrimitiveProperty().size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithSomeProperties() throws Exception { String name = "Mattias"; Node node = createNodeAndLoadFresh( map( "age", 5, "name", name ), 0, 0 ); assertEquals( withNodeOverhead( properties().withSmallPrimitiveProperty().withStringProperty( name ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithOneRelationship() throws Exception { Node node = createNodeAndLoadFresh( map(), 1, 1 ); assertEquals( withNodeOverhead( relationships().add( array().withOutRelationships( 1 ) ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithSomeRelationshipsOfSameType() throws Exception { Node node = createNodeAndLoadFresh( map(), 10, 1 ); assertEquals( withNodeOverhead( relationships().add( array().withOutRelationships( 10 ) ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithSomeRelationshipOfDifferentTypes() throws Exception { Node node = createNodeAndLoadFresh( map(), 3, 3 ); assertEquals( withNodeOverhead( relationships().add( array().withOutRelationships( 3 ) ).add( array().withOutRelationships( 3 ) ).add( array().withOutRelationships( 3 ) ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithSomeRelationshipOfDifferentTypesAndDirections() throws Exception { Node node = createNodeAndLoadFresh( map(), 9, 3, 1 ); assertEquals( withNodeOverhead( relationships().add( array().withRelationshipInAllDirections( 3 ) ).add( array().withRelationshipInAllDirections( 3 ) ).add( array().withRelationshipInAllDirections( 3 ) ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfNodeWithRelationshipsAndProperties() throws Exception { int[] array = new int[]{10, 11, 12, 13}; Node node = createNodeAndLoadFresh( map( "age", 10, "array", array ), 9, 3, 1 ); assertEquals( withNodeOverhead( relationships().add( array().withRelationshipInAllDirections( 3 ) ).add( array().withRelationshipInAllDirections( 3 ) ).add( array().withRelationshipInAllDirections( 3 ) ).size() + properties().withSmallPrimitiveProperty().withArrayProperty( array ).size() ), sizeOfNode( node ) ); } @Test public void sizeOfEmptyRelationship() throws Exception { Relationship relationship = createRelationshipAndLoadFresh( map() ); assertEquals( withRelationshipOverhead( 0 ), sizeOfRelationship( relationship ) ); } @Test public void sizeOfRelationshipWithOneProperty() throws Exception { Relationship relationship = createRelationshipAndLoadFresh( map( "age", 5 ) ); assertEquals( withRelationshipOverhead( properties().withSmallPrimitiveProperty().size() ), sizeOfRelationship( relationship ) ); } @Test public void sizeOfRelationshipWithSomeProperties() throws Exception { String name = "Mattias"; Relationship relationship = createRelationshipAndLoadFresh( map( "age", 5, "name", name ) ); assertEquals( withRelationshipOverhead( properties().withSmallPrimitiveProperty().withStringProperty( name ).size() ), sizeOfRelationship( relationship ) ); } @Test public void assumeWorstCaseJavaObjectOverhead() throws Exception { int size = 88; assertEquals( size+16, withObjectOverhead( size ) ); } @Test public void assumeWorstCaseJavaArrayObjectOverhead() throws Exception { int size = 88; assertEquals( size+24, withArrayOverhead( size ) ); } @Test public void assumeWorstCaseJavaArrayObjectOverheadIncludingReferences() throws Exception { int size = 24; int length = 5; assertEquals( withArrayOverhead( size+REFERENCE_SIZE*length ), withArrayOverheadIncludingReferences( size, length ) ); } @Test public void assumeWorstCaseReferenceToJavaObject() throws Exception { int size = 24; assertEquals( size + REFERENCE_SIZE, withReference( size ) ); } @Test public void sizeOfPrimitiveArrayIsCorrectlyCalculated() throws Exception { assertArraySize( new boolean[] { true, false }, 1 ); assertArraySize( new byte[] { 1, 2, 3 }, 1 ); assertArraySize( new short[] { 23, 21, 1, 45 }, 2 ); assertArraySize( new int[] { 100, 121, 1, 3, 45 }, 4 ); assertArraySize( new long[] { 403L, 3849329L, 23829L }, 8 ); assertArraySize( new float[] { 342.0F, 21F, 43.4567F }, 4 ); assertArraySize( new double[] { 45748.98D, 38493D }, 8 ); // 32 includes the reference to the Integer item (8), object overhead (16) and int value w/ padding (8) assertArraySize( new Integer[] { 123, 456, 789 }, 32 ); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestSizeOf.java
852
private static class LruCacheTest<K,E> extends LruCache<K,E> { private Object cleanedElement = null; LruCacheTest( String name, int maxSize ) { super( name, maxSize ); } @Override public void elementCleaned( E element ) { cleanedElement = element; } Object getLastCleanedElement() { return cleanedElement; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestLruCache.java
853
public class TestLruCache { @Test public void testCreate() { try { new LruCache<Object,Object>( "TestCache", 0 ); fail( "Illegal maxSize should throw exception" ); } catch ( IllegalArgumentException e ) { // good } LruCache<Object,Object> cache = new LruCache<Object,Object>( "TestCache", 70 ); try { cache.put( null, new Object() ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.put( new Object(), null ); fail( "Null element should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.get( null ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } try { cache.remove( null ); fail( "Null key should throw exception" ); } catch ( IllegalArgumentException e ) { // good } cache.put( new Object(), new Object() ); cache.clear(); } private static class LruCacheTest<K,E> extends LruCache<K,E> { private Object cleanedElement = null; LruCacheTest( String name, int maxSize ) { super( name, maxSize ); } @Override public void elementCleaned( E element ) { cleanedElement = element; } Object getLastCleanedElement() { return cleanedElement; } } @Test public void testSimple() { LruCacheTest<Object,Object> cache = new LruCacheTest<Object,Object>( "TestCache", 3 ); String s1 = new String( "1" ); Integer key1 = new Integer( 1 ); String s2 = new String( "2" ); Integer key2 = new Integer( 2 ); String s3 = new String( "3" ); Integer key3 = new Integer( 3 ); String s4 = new String( "4" ); Integer key4 = new Integer( 4 ); String s5 = new String( "5" ); Integer key5 = new Integer( 5 ); cache.put( key1, s1 ); cache.put( key2, s2 ); cache.put( key3, s3 ); cache.get( key2 ); assertEquals( null, cache.getLastCleanedElement() ); cache.put( key4, s4 ); assertEquals( s1, cache.getLastCleanedElement() ); cache.put( key5, s5 ); assertEquals( s3, cache.getLastCleanedElement() ); int size = cache.size(); assertEquals( 3, size ); assertEquals( null, cache.get( key1 ) ); assertEquals( s2, cache.get( key2 ) ); assertEquals( null, cache.get( key3 ) ); assertEquals( s4, cache.get( key4 ) ); assertEquals( s5, cache.get( key5 ) ); cache.clear(); assertEquals( 0, cache.size() ); } @Test public void testResize() { LruCacheTest<Object,Object> cache = new LruCacheTest<Object,Object>( "TestCache", 3 ); String s1 = new String( "1" ); Integer key1 = new Integer( 1 ); String s2 = new String( "2" ); Integer key2 = new Integer( 2 ); String s3 = new String( "3" ); Integer key3 = new Integer( 3 ); String s4 = new String( "4" ); Integer key4 = new Integer( 4 ); String s5 = new String( "5" ); Integer key5 = new Integer( 5 ); cache.put( key1, s1 ); cache.put( key2, s2 ); cache.put( key3, s3 ); cache.get( key2 ); assertEquals( null, cache.getLastCleanedElement() ); assertEquals( cache.maxSize(), cache.size() ); cache.resize( 5 ); assertEquals( 5, cache.maxSize() ); assertEquals( 3, cache.size() ); cache.put( key4, s4 ); assertEquals( null, cache.getLastCleanedElement() ); cache.put( key5, s5 ); assertEquals( null, cache.getLastCleanedElement() ); assertEquals( cache.maxSize(), cache.size() ); cache.resize( 4 ); assertEquals( s1, cache.getLastCleanedElement() ); assertEquals( cache.maxSize(), cache.size() ); cache.resize( 3 ); assertEquals( s3, cache.getLastCleanedElement() ); assertEquals( 3, cache.maxSize() ); assertEquals( 3, cache.size() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_cache_TestLruCache.java
854
{ @Override public void run() { nodeCache.remove( node.getId() ); } };
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCacheRemoveSizeDiverge.java
855
{ @Override public void run() { // It will break in NodeImpl#loadInitialRelationships right before calling updateSize Transaction transaction = graphdb.beginTx(); try { count( node.getRelationships() ); } finally { transaction.finish(); } } };
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCacheRemoveSizeDiverge.java
856
@ForeignBreakpoints( { @ForeignBreakpoints.BreakpointDef( type = "org.neo4j.kernel.impl.core.NodeImpl", method = "updateSize" ) } ) @RunWith( SubProcessTestRunner.class ) public class TestHighPerformanceCacheRemoveSizeDiverge { private static GraphDatabaseAPI graphdb; private static DebuggedThread thread; private static CountDownLatch latch = new CountDownLatch( 1 ); @BeforeClass public static void startDb() { try { graphdb = (GraphDatabaseAPI) new GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( forTest(TestHighPerformanceCacheRemoveSizeDiverge.class ).makeGraphDbDir( ).getAbsolutePath()). setConfig( stringMap( GraphDatabaseSettings.cache_type.name(), HighPerformanceCacheProvider.NAME ) ). newGraphDatabase(); } catch ( Throwable t ) { t.printStackTrace(); } } @AfterClass public static void shutdownDb() { try { if ( graphdb != null ) graphdb.shutdown(); } finally { graphdb = null; } } private Node createNodeWithSomeRelationships() { Transaction tx = graphdb.beginTx(); try { Node node = graphdb.createNode(); for ( int i = 0; i < 10; i++ ) node.createRelationshipTo( node, MyRelTypes.TEST ); tx.success(); return node; } finally { tx.finish(); } } @BreakpointHandler( "updateSize" ) public static void onUpdateSize( BreakPoint self, DebugInterface di ) { self.disable(); thread = di.thread().suspend( null ); latch.countDown(); } @BreakpointHandler( "resumeUpdateSize" ) public static void onResumeUpdateSize( BreakPoint self, DebugInterface di ) { thread.resume(); } @BreakpointTrigger( "resumeUpdateSize" ) private void resumeUpdateSize() {} @BreakpointTrigger( "enableBreakpoints" ) private void enableBreakpoints() {} @BreakpointHandler( "enableBreakpoints" ) public static void onEnableBreakpoints( @BreakpointHandler( "updateSize" ) BreakPoint updateSize, DebugInterface di ) { updateSize.enable(); } @Test @EnabledBreakpoints( { "enableBreakpoints", "resumeUpdateSize" } ) public void removeFromCacheInBetweenOtherThreadStateChangeAndUpdateSize() throws Exception { // ...should yield a size which matches actual cache size /* Here's the English version of how to trigger it: * T1: create node N with 10 relationships * T1: clear cache (simulating that it needs to be loaded for the first time the next access) * T1: request N so that it gets put into cache (no relationships loaded) * T1: load relationships of N, break right before call to NodeImpl#updateSize * T2: remove N from cache, which calls N.size() which will return a size different from * what the cache thinks that object is so it will subtract more than it should. * T1: resume execution * * => cache size should be 0, but the bug makes it less than zero. Over time the cache will * diverge more and more from actual cache size. */ final Node node = createNodeWithSomeRelationships(); graphdb.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); enableBreakpoints(); Transaction transaction = graphdb.beginTx(); try { graphdb.getNodeById( node.getId() ); } finally { transaction.finish(); } final Cache<?> nodeCache = graphdb.getDependencyResolver().resolveDependency( NodeManager.class ).caches().iterator().next(); assertTrue( "We didn't get a hold of the right cache object", nodeCache.getName().toLowerCase().contains( "node" ) ); Thread t1 = new Thread( "T1: Relationship loader" ) { @Override public void run() { // It will break in NodeImpl#loadInitialRelationships right before calling updateSize Transaction transaction = graphdb.beginTx(); try { count( node.getRelationships() ); } finally { transaction.finish(); } } }; t1.start(); // TODO wait for latch instead, but it seems to be a different instance than the one we countDown. // latch.await(); Thread.sleep( 2000 ); Thread t2 = new Thread( "T2: Cache remover" ) { @Override public void run() { nodeCache.remove( node.getId() ); } }; t2.start(); t2.join(); resumeUpdateSize(); t1.join(); assertEquals( "Invalid cache size for " + nodeCache, 0, nodeCache.size() ); } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCacheRemoveSizeDiverge.java
857
private static abstract class SneakyEntity extends Entity { SneakyEntity( long id, int size ) { super( id, size ); } @Override public int sizeOfObjectInBytesIncludingOverhead() { int size = super.sizeOfObjectInBytesIncludingOverhead(); doThisBadStuffInSizeCall(); return size; } abstract void doThisBadStuffInSizeCall(); }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
858
private static class Entity implements EntityWithSizeObject { private final long id; private int size; private int registeredSize; Entity( long id, int size ) { this.id = id; this.size = size; } @Override public int sizeOfObjectInBytesIncludingOverhead() { return size; } @Override public long getId() { return id; } public void updateSize( int newSize ) { this.size = newSize; } @Override public void setRegisteredSize( int size ) { this.registeredSize = size; } @Override public int getRegisteredSize() { return registeredSize; } }
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
859
{ @Override void doThisBadStuffInSizeCall() { // when AAC.remove asks the object for size this will emulate a cache.updateSize( oldObj, size, size + 1 ) updateSize( size + 1 ); cache.updateSize( this, size + 1 ); } };
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
860
{ @Override void doThisBadStuffInSizeCall() { // when AAC.put asks the old object for size this will emulate a cache.updateSize( oldObj, size, size + 1 ) updateSize( size + 1 ); cache.updateSize( this, size + 1 ); } };
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
861
{ @Override protected int getPosition( EntityWithSizeObject obj ) { // For this test case return the same position every time. return 1; } };
false
enterprise_ha_src_test_java_org_neo4j_kernel_impl_cache_TestHighPerformanceCache.java
862
{ @Override public int compare( Object o1, Object o2 ) { return ((RelIdArray) o1).getType() - (Integer) o2; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeImpl.java
863
public class NodeImplTest { private static final int TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE = 0; private static final long TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID = 1; /** * This behaviour is a workaround until we have proper concurrency support in the kernel. * It fixes a problem at the lower levels whereby a source containing a relationship from disk * gets merged with a add COW map containing the same relationship in an uncommitted transaction * giving unhelpful duplicates at the API level. One day this unit test can be removed, * but that day is not today. */ @Test public void shouldQuietlyIgnoreSingleDuplicateEntryWhenGetSingleRelationshipCalled() throws Exception { // given NodeImpl nodeImpl = new NodeImpl( 1 ); RelationshipType loves = DynamicRelationshipType.withName( "LOVES" ); TransactionState txState = mock( TransactionState.class ); ThreadToStatementContextBridge stmCtxBridge = mock( ThreadToStatementContextBridge.class ); NodeManager nodeManager = mock( NodeManager.class ); RelationshipProxy.RelationshipLookups relLookup = mock( RelationshipProxy.RelationshipLookups.class ); when( relLookup.getNodeManager() ).thenReturn( nodeManager ); when( nodeManager.getRelationshipTypeById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE ) ) .thenReturn( loves ); when( relLookup.lookupRelationship( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ) .thenReturn( new RelationshipImpl( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, 1, 2, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, false ) ); when( nodeManager.getMoreRelationships( nodeImpl ) ).thenReturn( tripletWithValues( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ).thenReturn( noMoreRelationshipsTriplet() ); when( nodeManager.getTransactionState() ).thenReturn( txState ); when( nodeManager.newRelationshipProxyById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ).thenReturn( new RelationshipProxy( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, relLookup, stmCtxBridge ) ); // when final Relationship singleRelationship = nodeImpl.getSingleRelationship( nodeManager, loves, Direction.OUTGOING ); // then assertNotNull( singleRelationship ); assertEquals( loves, singleRelationship.getType() ); } @Test public void shouldThrowExceptionIfMultipleDifferentEntries() throws Exception { // given NodeImpl nodeImpl = new NodeImpl( 1 ); RelationshipType loves = DynamicRelationshipType.withName( "LOVES" ); TransactionState txState = mock( TransactionState.class ); ThreadToStatementContextBridge stmCtxBridge = mock( ThreadToStatementContextBridge.class ); NodeManager nodeManager = mock( NodeManager.class ); RelationshipProxy.RelationshipLookups relLookup = mock( RelationshipProxy.RelationshipLookups.class ); when( relLookup.getNodeManager() ).thenReturn( nodeManager ); when( nodeManager.getRelationshipTypeById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE ) ) .thenReturn( loves ); when( relLookup.lookupRelationship( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ) .thenReturn( new RelationshipImpl( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, 1, 2, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, false ) ); when( relLookup.lookupRelationship( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ) .thenReturn( new RelationshipImpl( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1, 1, 2, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, false ) ); when( nodeManager.getMoreRelationships( nodeImpl ) ).thenReturn( tripletWithValues( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ).thenReturn( noMoreRelationshipsTriplet() ); when( nodeManager.getTransactionState() ).thenReturn( txState ); when( nodeManager.newRelationshipProxyById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ) .thenReturn( new RelationshipProxy( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, relLookup, stmCtxBridge ) ); when( nodeManager.newRelationshipProxyById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ) .thenReturn( new RelationshipProxy( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1, relLookup, stmCtxBridge ) ); // when try { nodeImpl.getSingleRelationship( nodeManager, loves, Direction.OUTGOING ); fail(); } catch ( NotFoundException expected ) { } } private Triplet<ArrayMap<Integer, RelIdArray>, List<RelationshipImpl>, Long> noMoreRelationshipsTriplet() { return Triplet.of( new ArrayMap<Integer, RelIdArray>(), Collections.<RelationshipImpl>emptyList(), 0l ); } @Test public void shouldThrowExceptionIfMultipleDifferentEntriesWithTwoOfThemBeingIdentical() throws Exception { // given NodeImpl nodeImpl = new NodeImpl( 1 ); RelationshipType loves = DynamicRelationshipType.withName( "LOVES" ); TransactionState txState = mock( TransactionState.class ); ThreadToStatementContextBridge stmCtxBridge = mock( ThreadToStatementContextBridge.class ); NodeManager nodeManager = mock( NodeManager.class ); RelationshipProxy.RelationshipLookups relLookup = mock( RelationshipProxy.RelationshipLookups.class ); when( relLookup.getNodeManager() ).thenReturn( nodeManager ); when( nodeManager.getRelationshipTypeById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE ) ) .thenReturn( loves ); when( relLookup.lookupRelationship( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ) .thenReturn( new RelationshipImpl( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, 1, 2, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, false ) ); when( relLookup.lookupRelationship( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ) .thenReturn( new RelationshipImpl( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1, 1, 2, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, false ) ); when( nodeManager.getMoreRelationships( nodeImpl ) ).thenReturn( tripletWithValues( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ).thenReturn( noMoreRelationshipsTriplet() ); when( nodeManager.getTransactionState() ).thenReturn( txState ); when( nodeManager.newRelationshipProxyById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID ) ) .thenReturn( new RelationshipProxy( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID, relLookup, stmCtxBridge ) ); when( nodeManager.newRelationshipProxyById( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1 ) ) .thenReturn( new RelationshipProxy( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_ID + 1, relLookup, stmCtxBridge) ); // when try { nodeImpl.getSingleRelationship( nodeManager, loves, Direction.OUTGOING ); fail(); } catch ( NotFoundException expected ) { } } private Triplet<ArrayMap<Integer, RelIdArray>, List<RelationshipImpl>, Long> tripletWithValues( long... ids ) { final RelIdArray relIdArray = createRelIdArrayWithValues( ids ); ArrayMap<Integer, RelIdArray> arrayMap = new ArrayMap<Integer, RelIdArray>(); arrayMap.put( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE, relIdArray ); return Triplet.of( arrayMap, Collections.<RelationshipImpl>emptyList(), 0l ); } private RelIdArray createRelIdArrayWithValues( long... ids ) { RelIdArray relIdArray = new RelIdArray( TOTALLY_ARBITRARY_VALUE_DENOTING_RELATIONSHIP_TYPE ); for ( long id : ids ) { relIdArray.add( id, RelIdArray.DirectionWrapper.OUTGOING ); } return relIdArray; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeImplTest.java
864
public class NodeManager implements Lifecycle, EntityFactory { private final StringLogger logger; private final GraphDatabaseService graphDbService; private final AutoLoadingCache<NodeImpl> nodeCache; private final AutoLoadingCache<RelationshipImpl> relCache; private final CacheProvider cacheProvider; private final AbstractTransactionManager transactionManager; private final PropertyKeyTokenHolder propertyKeyTokenHolder; private final LabelTokenHolder labelTokenHolder; private final RelationshipTypeTokenHolder relTypeHolder; private final PersistenceManager persistenceManager; private final EntityIdGenerator idGenerator; private final XaDataSourceManager xaDsm; private final ThreadToStatementContextBridge statementCtxProvider; private final NodeProxy.NodeLookup nodeLookup; private final RelationshipProxy.RelationshipLookups relationshipLookups; private final RelationshipLoader relationshipLoader; private final List<PropertyTracker<Node>> nodePropertyTrackers; private final List<PropertyTracker<Relationship>> relationshipPropertyTrackers; private GraphPropertiesImpl graphProperties; private final AutoLoadingCache.Loader<NodeImpl> nodeLoader = new AutoLoadingCache.Loader<NodeImpl>() { @Override public NodeImpl loadById( long id ) { NodeRecord record = persistenceManager.loadLightNode( id ); if ( record == null ) { return null; } return new NodeImpl( id ); } }; private final AutoLoadingCache.Loader<RelationshipImpl> relLoader = new AutoLoadingCache.Loader<RelationshipImpl>() { @Override public RelationshipImpl loadById( long id ) { RelationshipRecord data = persistenceManager.loadLightRelationship( id ); if ( data == null ) { return null; } int typeId = data.getType(); final long startNodeId = data.getFirstNode(); final long endNodeId = data.getSecondNode(); return new RelationshipImpl( id, startNodeId, endNodeId, typeId, false ); } }; public NodeManager( StringLogger logger, GraphDatabaseService graphDb, AbstractTransactionManager transactionManager, PersistenceManager persistenceManager, EntityIdGenerator idGenerator, RelationshipTypeTokenHolder relationshipTypeTokenHolder, CacheProvider cacheProvider, PropertyKeyTokenHolder propertyKeyTokenHolder, LabelTokenHolder labelTokenHolder, NodeProxy.NodeLookup nodeLookup, RelationshipProxy.RelationshipLookups relationshipLookups, Cache<NodeImpl> nodeCache, Cache<RelationshipImpl> relCache, XaDataSourceManager xaDsm, ThreadToStatementContextBridge statementCtxProvider ) { this.logger = logger; this.graphDbService = graphDb; this.transactionManager = transactionManager; this.propertyKeyTokenHolder = propertyKeyTokenHolder; this.persistenceManager = persistenceManager; this.idGenerator = idGenerator; this.labelTokenHolder = labelTokenHolder; this.nodeLookup = nodeLookup; this.relationshipLookups = relationshipLookups; this.relTypeHolder = relationshipTypeTokenHolder; this.cacheProvider = cacheProvider; this.statementCtxProvider = statementCtxProvider; this.nodeCache = new AutoLoadingCache<>( nodeCache, nodeLoader ); this.relCache = new AutoLoadingCache<>( relCache, relLoader ); this.xaDsm = xaDsm; nodePropertyTrackers = new LinkedList<>(); relationshipPropertyTrackers = new LinkedList<>(); this.relationshipLoader = new RelationshipLoader( persistenceManager, relCache ); this.graphProperties = instantiateGraphProperties(); } public GraphDatabaseService getGraphDbService() { return graphDbService; } public CacheProvider getCacheType() { return this.cacheProvider; } @Override public void init() { // Nothing to initialize } @Override public void start() { for ( XaDataSource ds : xaDsm.getAllRegisteredDataSources() ) { if ( ds.getName().equals( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ) ) { NeoStore neoStore = ((NeoStoreXaDataSource) ds).getNeoStore(); TokenStore<?> propTokens = neoStore.getPropertyStore().getPropertyKeyTokenStore(); TokenStore<?> labelTokens = neoStore.getLabelTokenStore(); TokenStore<?> relTokens = neoStore.getRelationshipTypeStore(); addRawRelationshipTypes( relTokens.getTokens( Integer.MAX_VALUE ) ); addPropertyKeyTokens( propTokens.getTokens( Integer.MAX_VALUE ) ); addLabelTokens( labelTokens.getTokens( Integer.MAX_VALUE ) ); } } } @Override public void stop() { clearCache(); } @Override public void shutdown() { nodeCache.printStatistics(); relCache.printStatistics(); nodeCache.clear(); relCache.clear(); } public Node createNode() { long id = idGenerator.nextId( Node.class ); NodeImpl node = new NodeImpl( id, true ); NodeProxy proxy = new NodeProxy( id, nodeLookup, statementCtxProvider ); TransactionState transactionState = getTransactionState(); transactionState.acquireWriteLock( proxy ); boolean success = false; try { persistenceManager.nodeCreate( id ); transactionState.createNode( id ); nodeCache.put( node ); success = true; return proxy; } finally { if ( !success ) { setRollbackOnly(); } } } @Override public NodeProxy newNodeProxyById( long id ) { return new NodeProxy( id, nodeLookup, statementCtxProvider ); } public Relationship createRelationship( Node startNodeProxy, NodeImpl startNode, Node endNode, long relationshipTypeId ) { if ( startNode == null || endNode == null || relationshipTypeId > Integer.MAX_VALUE ) { throw new IllegalArgumentException( "Bad parameter, startNode=" + startNode + ", endNode=" + endNode + ", typeId=" + relationshipTypeId ); } int typeId = (int)relationshipTypeId; long startNodeId = startNode.getId(); long endNodeId = endNode.getId(); NodeImpl secondNode = getLightNode( endNodeId ); if ( secondNode == null ) { setRollbackOnly(); throw new NotFoundException( "Second node[" + endNode.getId() + "] deleted" ); } long id = idGenerator.nextId( Relationship.class ); RelationshipImpl rel = new RelationshipImpl( id, startNodeId, endNodeId, typeId, true ); RelationshipProxy proxy = new RelationshipProxy( id, relationshipLookups, statementCtxProvider ); TransactionState tx = getTransactionState(); tx.acquireWriteLock( proxy ); boolean success = false; try { tx.acquireWriteLock( startNodeProxy ); tx.acquireWriteLock( endNode ); persistenceManager.relationshipCreate( id, typeId, startNodeId, endNodeId ); tx.createRelationship( id ); if ( startNodeId == endNodeId ) { tx.getOrCreateCowRelationshipAddMap( startNode, typeId ).add( id, DirectionWrapper.BOTH ); } else { tx.getOrCreateCowRelationshipAddMap( startNode, typeId ).add( id, DirectionWrapper.OUTGOING ); tx.getOrCreateCowRelationshipAddMap( secondNode, typeId ).add( id, DirectionWrapper.INCOMING ); } // relCache.put( rel.getId(), rel ); relCache.put( rel ); success = true; return proxy; } finally { if ( !success ) { setRollbackOnly(); } } } public Node getNodeByIdOrNull( long nodeId ) { transactionManager.assertInTransaction(); NodeImpl node = getLightNode( nodeId ); return node != null ? new NodeProxy( nodeId, nodeLookup, statementCtxProvider ) : null; } public Node getNodeById( long nodeId ) throws NotFoundException { Node node = getNodeByIdOrNull( nodeId ); if ( node == null ) { throw new NotFoundException( format( "Node %d not found", nodeId ) ); } return node; } NodeImpl getLightNode( long nodeId ) { return nodeCache.get( nodeId ); } @Override public RelationshipProxy newRelationshipProxyById( long id ) { return new RelationshipProxy( id, relationshipLookups, statementCtxProvider ); } public Iterator<Node> getAllNodes() { Iterator<Node> committedNodes = new PrefetchingIterator<Node>() { private long highId = getHighestPossibleIdInUse( Node.class ); private long currentId; @Override protected Node fetchNextOrNull() { while ( true ) { // This outer loop is for checking if highId has changed since we started. while ( currentId <= highId ) { try { Node node = getNodeByIdOrNull( currentId ); if ( node != null ) { return node; } } finally { currentId++; } } long newHighId = getHighestPossibleIdInUse( Node.class ); if ( newHighId > highId ) { highId = newHighId; } else { break; } } return null; } }; final TransactionState txState = getTransactionState(); if ( !txState.hasChanges() ) { return committedNodes; } /* Created nodes are put in the cache right away, even before the transaction is committed. * We want this iterator to include nodes that have been created, but not yes committed in * this transaction. The thing with the cache is that stuff can be evicted at any point in time * so we can't rely on created nodes to be there during the whole life time of this iterator. * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/ final Set<Long> createdNodes = new HashSet<>( txState.getCreatedNodes() ); if ( !createdNodes.isEmpty() ) { committedNodes = new FilteringIterator<>( committedNodes, new Predicate<Node>() { @Override public boolean accept( Node node ) { return !createdNodes.contains( node.getId() ); } } ); } // Filter out nodes deleted in this transaction Iterator<Node> filteredRemovedNodes = new FilteringIterator<>( committedNodes, new Predicate<Node>() { @Override public boolean accept( Node node ) { return !txState.nodeIsDeleted( node.getId() ); } } ); // Append nodes created in this transaction return new CombiningIterator<>( asList( filteredRemovedNodes, new IteratorWrapper<Node, Long>( createdNodes.iterator() ) { @Override protected Node underlyingObjectToObject( Long id ) { return getNodeById( id ); } } ) ); } /** * TODO: We only grab this lock in one single place, from inside the kernel: * {@link org.neo4j.kernel.impl.api.DefaultLegacyKernelOperations#relationshipCreate(org.neo4j.kernel.api.Statement, long, long, long)}. * We should move that code around such that this lock is grabbed through the locking layer in the kernel cake, and * then we should remove this locking code. It is dangerous to have it here, because it allows grabbing a lock * before the kernel is registered as a data source. If that happens in HA, we will attempt to grab locks on the * master before the transaction is started on the master. */ public NodeImpl getNodeForProxy( long nodeId, LockType lock ) { if ( lock != null ) { lock.acquire( getTransactionState(), new NodeProxy( nodeId, nodeLookup, statementCtxProvider ) ); } NodeImpl node = getLightNode( nodeId ); if ( node == null ) { throw new NotFoundException( format( "Node %d not found", nodeId ) ); } return node; } protected Relationship getRelationshipByIdOrNull( long relId ) { transactionManager.assertInTransaction(); RelationshipImpl relationship = relCache.get( relId ); return relationship != null ? new RelationshipProxy( relId, relationshipLookups, statementCtxProvider ) : null; } public Relationship getRelationshipById( long id ) throws NotFoundException { Relationship relationship = getRelationshipByIdOrNull( id ); if ( relationship == null ) { throw new NotFoundException( format( "Relationship %d not found", id ) ); } return relationship; } public Iterator<Relationship> getAllRelationships() { Iterator<Relationship> committedRelationships = new PrefetchingIterator<Relationship>() { private long highId = getHighestPossibleIdInUse( Relationship.class ); private long currentId; @Override protected Relationship fetchNextOrNull() { while ( true ) { // This outer loop is for checking if highId has changed since we started. while ( currentId <= highId ) { try { Relationship relationship = getRelationshipByIdOrNull( currentId ); if ( relationship != null ) { return relationship; } } finally { currentId++; } } long newHighId = getHighestPossibleIdInUse( Node.class ); if ( newHighId > highId ) { highId = newHighId; } else { break; } } return null; } }; final TransactionState txState = getTransactionState(); if ( !txState.hasChanges() ) { return committedRelationships; } /* Created relationships are put in the cache right away, even before the transaction is committed. * We want this iterator to include relationships that have been created, but not yes committed in * this transaction. The thing with the cache is that stuff can be evicted at any point in time * so we can't rely on created relationships to be there during the whole life time of this iterator. * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/ final Set<Long> createdRelationships = new HashSet<>( txState.getCreatedRelationships() ); if ( !createdRelationships.isEmpty() ) { committedRelationships = new FilteringIterator<>( committedRelationships, new Predicate<Relationship>() { @Override public boolean accept( Relationship relationship ) { return !createdRelationships.contains( relationship.getId() ); } } ); } // Filter out relationships deleted in this transaction Iterator<Relationship> filteredRemovedRelationships = new FilteringIterator<>( committedRelationships, new Predicate<Relationship>() { @Override public boolean accept( Relationship relationship ) { return !txState.relationshipIsDeleted( relationship.getId() ); } } ); // Append relationships created in this transaction return new CombiningIterator<>( asList( filteredRemovedRelationships, new IteratorWrapper<Relationship, Long>( createdRelationships.iterator() ) { @Override protected Relationship underlyingObjectToObject( Long id ) { return getRelationshipById( id ); } } ) ); } RelationshipType getRelationshipTypeById( int id ) throws TokenNotFoundException { return relTypeHolder.getTokenById( id ); } public RelationshipImpl getRelationshipForProxy( long relId ) { RelationshipImpl rel = relCache.get( relId ); if ( rel == null ) { throw new NotFoundException( format( "Relationship %d not found", relId ) ); } return rel; } public void removeNodeFromCache( long nodeId ) { nodeCache.remove( nodeId ); } public void removeRelationshipFromCache( long id ) { relCache.remove( id ); } public void patchDeletedRelationshipNodes( long relId, long firstNodeId, long firstNodeNextRelId, long secondNodeId, long secondNodeNextRelId ) { invalidateNode( firstNodeId, relId, firstNodeNextRelId ); invalidateNode( secondNodeId, relId, secondNodeNextRelId ); } private void invalidateNode( long nodeId, long relIdDeleted, long nextRelId ) { NodeImpl node = nodeCache.getIfCached( nodeId ); if ( node != null && node.getRelChainPosition() == relIdDeleted ) { node.setRelChainPosition( nextRelId ); } } long getRelationshipChainPosition( NodeImpl node ) { return persistenceManager.getRelationshipChainPosition( node.getId() ); } void putAllInRelCache( Collection<RelationshipImpl> relationships ) { relCache.putAll( relationships ); } Iterator<DefinedProperty> loadGraphProperties( boolean light ) { IteratingPropertyReceiver receiver = new IteratingPropertyReceiver(); persistenceManager.graphLoadProperties( light, receiver ); return receiver; } Iterator<DefinedProperty> loadProperties( NodeImpl node, boolean light ) { IteratingPropertyReceiver receiver = new IteratingPropertyReceiver(); persistenceManager.loadNodeProperties( node.getId(), light, receiver ); return receiver; } Iterator<DefinedProperty> loadProperties( RelationshipImpl relationship, boolean light ) { IteratingPropertyReceiver receiver = new IteratingPropertyReceiver(); persistenceManager.loadRelProperties( relationship.getId(), light, receiver ); return receiver; } public void clearCache() { nodeCache.clear(); relCache.clear(); graphProperties = instantiateGraphProperties(); } public Iterable<? extends Cache<?>> caches() { return asList( nodeCache, relCache ); } public void setRollbackOnly() { try { transactionManager.setRollbackOnly(); } catch ( IllegalStateException e ) { // this exception always get generated in a finally block and // when it happens another exception has already been thrown // (most likely NotInTransactionException) logger.debug( "Failed to set transaction rollback only", e ); } catch ( javax.transaction.SystemException se ) { // our TM never throws this exception logger.error( "Failed to set transaction rollback only", se ); } } public <T extends PropertyContainer> T indexPutIfAbsent( Index<T> index, T entity, String key, Object value ) { T existing = index.get( key, value ).getSingle(); if ( existing != null ) { return existing; } // Grab lock IndexLock lock = new IndexLock( index.getName(), key ); TransactionState state = getTransactionState(); LockElement writeLock = state.acquireWriteLock( lock ); // Check again -- now holding the lock existing = index.get( key, value ).getSingle(); if ( existing != null ) { // Someone else created this entry, release the lock as we won't be needing it writeLock.release(); return existing; } // Add index.add( entity, key, value ); return null; } public long getHighestPossibleIdInUse( Class<?> clazz ) { return idGenerator.getHighestPossibleIdInUse( clazz ); } public long getNumberOfIdsInUse( Class<?> clazz ) { return idGenerator.getNumberOfIdsInUse( clazz ); } public void removeRelationshipTypeFromCache( int id ) { relTypeHolder.removeToken( id ); } void addPropertyKeyTokens( Token[] propertyKeyTokens ) { propertyKeyTokenHolder.addTokens( propertyKeyTokens ); } void addLabelTokens( Token[] labelTokens ) { labelTokenHolder.addTokens( labelTokens ); } Token getPropertyKeyTokenOrNull( String key ) { return propertyKeyTokenHolder.getTokenByNameOrNull( key ); } int getRelationshipTypeIdFor( RelationshipType type ) { return relTypeHolder.getIdByName( type.name() ); } void addRawRelationshipTypes( Token[] relTypes ) { relTypeHolder.addTokens( relTypes ); } public Iterable<RelationshipType> getRelationshipTypes() { return cast( relTypeHolder.getAllTokens() ); } public ArrayMap<Integer, DefinedProperty> deleteNode( NodeImpl node, TransactionState tx ) { tx.deleteNode( node.getId() ); return persistenceManager.nodeDelete( node.getId() ); // remove from node cache done via event } public ArrayMap<Integer, DefinedProperty> deleteRelationship( RelationshipImpl rel, TransactionState tx ) { NodeImpl startNode; NodeImpl endNode; boolean success = false; try { long startNodeId = rel.getStartNodeId(); startNode = getLightNode( startNodeId ); if ( startNode != null ) { tx.acquireWriteLock( newNodeProxyById( startNodeId ) ); } long endNodeId = rel.getEndNodeId(); endNode = getLightNode( endNodeId ); if ( endNode != null ) { tx.acquireWriteLock( newNodeProxyById( endNodeId ) ); } tx.acquireWriteLock( newRelationshipProxyById( rel.getId() ) ); // no need to load full relationship, all properties will be // deleted when relationship is deleted ArrayMap<Integer,DefinedProperty> skipMap = tx.getOrCreateCowPropertyRemoveMap( rel ); tx.deleteRelationship( rel.getId() ); ArrayMap<Integer,DefinedProperty> removedProps = persistenceManager.relDelete( rel.getId() ); if ( removedProps.size() > 0 ) { for ( int index : removedProps.keySet() ) { skipMap.put( index, removedProps.get( index ) ); } } int typeId = rel.getTypeId(); long id = rel.getId(); if ( startNode != null ) { tx.getOrCreateCowRelationshipRemoveMap( startNode, typeId ).add( id ); } if ( endNode != null ) { tx.getOrCreateCowRelationshipRemoveMap( endNode, typeId ).add( id ); } success = true; return removedProps; } finally { if ( !success ) { setRollbackOnly(); } } } public Triplet<ArrayMap<Integer, RelIdArray>, List<RelationshipImpl>, Long> getMoreRelationships( NodeImpl node ) { return relationshipLoader.getMoreRelationships( node ); } public NodeImpl getNodeIfCached( long nodeId ) { return nodeCache.getIfCached( nodeId ); } public RelationshipImpl getRelIfCached( long nodeId ) { return relCache.getIfCached( nodeId ); } public void addRelationshipTypeToken( Token type ) { relTypeHolder.addTokens( type ); } public void addLabelToken( Token type ) { labelTokenHolder.addTokens( type ); } public void addPropertyKeyToken( Token index ) { propertyKeyTokenHolder.addTokens( index ); } public String getKeyForProperty( DefinedProperty property ) { // int keyId = persistenceManager.getKeyIdForProperty( property ); try { return propertyKeyTokenHolder.getTokenById( property.propertyKeyId() ).name(); } catch ( TokenNotFoundException e ) { throw new ThisShouldNotHappenError( "Mattias", "The key should exist at this point" ); } } public List<PropertyTracker<Node>> getNodePropertyTrackers() { return nodePropertyTrackers; } public List<PropertyTracker<Relationship>> getRelationshipPropertyTrackers() { return relationshipPropertyTrackers; } public void addNodePropertyTracker( PropertyTracker<Node> nodePropertyTracker ) { nodePropertyTrackers.add( nodePropertyTracker ); } public void removeNodePropertyTracker( PropertyTracker<Node> nodePropertyTracker ) { nodePropertyTrackers.remove( nodePropertyTracker ); } public void addRelationshipPropertyTracker( PropertyTracker<Relationship> relationshipPropertyTracker ) { relationshipPropertyTrackers.add( relationshipPropertyTracker ); } public void removeRelationshipPropertyTracker( PropertyTracker<Relationship> relationshipPropertyTracker ) { relationshipPropertyTrackers.remove( relationshipPropertyTracker ); } // For compatibility reasons with Cypher public boolean isDeleted( PropertyContainer entity ) { if ( entity instanceof Node ) { return isDeleted( (Node) entity ); } else if ( entity instanceof Relationship ) { return isDeleted( (Relationship) entity ); } else { throw new IllegalArgumentException( "Unknown entity type: " + entity + ", " + entity.getClass() ); } } public boolean isDeleted( Node resource ) { return getTransactionState().nodeIsDeleted( resource.getId() ); } public boolean isDeleted( Relationship resource ) { return getTransactionState().relationshipIsDeleted( resource.getId() ); } private GraphPropertiesImpl instantiateGraphProperties() { return new GraphPropertiesImpl( this, statementCtxProvider ); } public GraphPropertiesImpl getGraphProperties() { return graphProperties; } public void removeGraphPropertiesFromCache() { graphProperties = instantiateGraphProperties(); } void updateCacheSize( NodeImpl node, int newSize ) { nodeCache.updateSize( node, newSize ); } void updateCacheSize( RelationshipImpl rel, int newSize ) { relCache.updateSize( rel, newSize ); } public TransactionState getTransactionState() { return transactionManager.getTransactionState(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
865
public class TestLoopRelationships extends AbstractNeo4jTestCase { @Test public void canCreateRelationshipBetweenTwoNodesWithLoopsThenDeleteOneOfTheNodesAndItsRelationships() throws Exception { Node source = getGraphDb().createNode(), target = getGraphDb().createNode(); source.createRelationshipTo( source, TEST ); target.createRelationshipTo( target, TEST ); source.createRelationshipTo( target, TEST ); newTransaction(); for ( Relationship rel : target.getRelationships() ) { rel.delete(); } target.delete(); } @Test public void canDeleteNodeAfterDeletingItsRelationshipsIfThoseRelationshipsIncludeLoops() throws Exception { Node node = getGraphDb().createNode(); txCreateLoop( node ); txCreateRel( node ); txCreateLoop( node ); node.delete(); for ( Relationship rel : node.getRelationships() ) { rel.delete(); } commit(); } private void txCreateRel( Node node ) { node.createRelationshipTo( getGraphDb().createNode(), TEST ); newTransaction(); } private void txCreateLoop( Node node ) { node.createRelationshipTo( node, TEST ); newTransaction(); } @Test public void canAddLoopRelationship() { Node node = getGraphDb().createNode(); node.createRelationshipTo( node, TEST ); newTransaction(); getNodeManager().clearCache(); for ( Direction dir : Direction.values() ) { int count = 0; for ( Relationship rel : node.getRelationships( dir ) ) { count++; assertEquals( "start node", node, rel.getStartNode() ); assertEquals( "end node", node, rel.getEndNode() ); assertEquals( "other node", node, rel.getOtherNode( node ) ); } assertEquals( dir.name() + " relationship count", 1, count ); } } @Test public void canAddManyLoopRelationships() { testAddManyLoopRelationships( 2 ); testAddManyLoopRelationships( 3 ); testAddManyLoopRelationships( 5 ); } private void testAddManyLoopRelationships( int count ) { for ( boolean[] loop : permutations( count ) ) { Node root = getGraphDb().createNode(); Relationship[] relationships = new Relationship[count]; for ( int i = 0; i < count; i++ ) { if ( loop[i] ) { relationships[i] = root.createRelationshipTo( root, TEST ); } else { relationships[i] = root.createRelationshipTo( getGraphDb().createNode(), TEST ); } } newTransaction(); verifyRelationships( Arrays.toString( loop ), root, loop, relationships ); } } @Test public void canAddLoopRelationshipAndOtherRelationships() { testAddLoopRelationshipAndOtherRelationships( 2 ); testAddLoopRelationshipAndOtherRelationships( 3 ); testAddLoopRelationshipAndOtherRelationships( 5 ); } private void testAddLoopRelationshipAndOtherRelationships( int size ) { for ( int i = 0; i < size; i++ ) { Node root = getGraphDb().createNode(); Relationship[] relationships = createRelationships( size, i, root ); verifyRelationships( String.format( "loop on %s of %s", i, size ), root, i, relationships ); } } @Test public void canAddAndRemoveLoopRelationshipAndOtherRelationships() { testAddAndRemoveLoopRelationshipAndOtherRelationships( 2 ); testAddAndRemoveLoopRelationshipAndOtherRelationships( 3 ); testAddAndRemoveLoopRelationshipAndOtherRelationships( 5 ); } @Test public void getSingleRelationshipOnNodeWithOneLoopOnly() throws Exception { Node node = getGraphDb().createNode(); Relationship singleRelationship = node.createRelationshipTo( node, TEST ); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.OUTGOING ) ); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.INCOMING ) ); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.BOTH ) ); commit(); newTransaction(); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.OUTGOING ) ); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.INCOMING ) ); assertEquals( singleRelationship, node.getSingleRelationship( TEST, Direction.BOTH ) ); finish(); } @Test public void cannotDeleteNodeWithLoopStillAttached() throws Exception { Node node = getGraphDb().createNode(); node.createRelationshipTo( node, TEST ); newTransaction(); node.delete(); try { commit(); fail( "Shouldn't be able to delete a node which still has a loop relationship attached" ); } catch ( TransactionFailureException e ) { // Good } } @Test public void getOtherNodeFunctionsCorrectly() throws Exception { Node node = getGraphDb().createNode(); Relationship relationship = node.createRelationshipTo( node, TEST ); // This loop messes up the readability of the test case, but avoids duplicated // assertion code. Same assertions withing the transaction as after it has committed. for ( int i = 0; i < 2; i++ ) { assertEquals( node, relationship.getOtherNode( node ) ); assertEquals( asList( node, node ), asList( relationship.getNodes() ) ); try { relationship.getOtherNode( getGraphDb().createNode() ); fail( "Should throw exception if another node is passed into loop.getOtherNode" ); } catch ( NotFoundException e ) { // Good } newTransaction(); } } @Test public void getNewlyCreatedLoopRelationshipFromCache() throws Exception { Node node = getGraphDb().createNode(); node.createRelationshipTo( getGraphDb().createNode(), TEST ); newTransaction(); Relationship relationship = node.createRelationshipTo( node, TEST ); newTransaction(); assertEquals( relationship, node.getSingleRelationship( TEST, Direction.INCOMING ) ); } private void testAddAndRemoveLoopRelationshipAndOtherRelationships( int size ) { for ( boolean[] delete : permutations( size ) ) { for ( int i = 0; i < size; i++ ) { Node root = getGraphDb().createNode(); Relationship[] relationships = createRelationships( size, i, root ); for ( int j = 0; j < size; j++ ) { if ( delete[j] ) { relationships[j].delete(); relationships[j] = null; } newTransaction(); } verifyRelationships( String.format( "loop on %s of %s, delete %s", i, size, Arrays.toString( delete ) ), root, i, relationships ); } } } private static Iterable<boolean[]> permutations( final int size ) { final int max = 1 << size; return new Iterable<boolean[]>() { public Iterator<boolean[]> iterator() { return new PrefetchingIterator<boolean[]>() { int pos = 0; @Override protected boolean[] fetchNextOrNull() { if ( pos < max ) { int cur = pos++; boolean[] result = new boolean[size]; for ( int i = 0; i < size; i++ ) { result[i] = ( cur & 1 ) == 1; cur >>= 1; } return result; } return null; } }; } }; } private Relationship[] createRelationships( int count, int loop, Node root ) { Node[] nodes = new Node[count]; for ( int i = 0; i < count; i++ ) { if ( loop == i ) { nodes[i] = root; } else { nodes[i] = getGraphDb().createNode(); } } newTransaction(); Relationship[] relationships = new Relationship[count]; for ( int i = 0; i < count; i++ ) { relationships[i] = root.createRelationshipTo( nodes[i], TEST ); newTransaction(); } return relationships; } private void verifyRelationships( String message, Node root, int loop, Relationship... relationships ) { boolean[] loops = new boolean[relationships.length]; for ( int i = 0; i < relationships.length; i++ ) { loops[i] = ( i == loop ); } verifyRelationships( message, root, loops, relationships ); } private void verifyRelationships( String message, Node root, boolean[] loop, Relationship... relationships ) { getNodeManager().clearCache(); for ( Direction dir : Direction.values() ) { Set<Relationship> expected = new HashSet<Relationship>(); for ( int i = 0; i < relationships.length; i++ ) { if ( relationships[i] != null && ( dir != Direction.INCOMING || loop[i] ) ) { expected.add( relationships[i] ); } } for ( Relationship rel : root.getRelationships( dir ) ) { assertTrue( message + ": unexpected relationship: " + rel, expected.remove( rel ) ); } assertTrue( message + ": expected relationships not seen " + expected, expected.isEmpty() ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLoopRelationships.java
866
private class ArrayRecordCounter implements DynamicRecordCounter { @Override public long count() { return dynamicArrayRecordsInUse(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLengthyArrayPacking.java
867
public class TestLengthyArrayPacking extends AbstractNeo4jTestCase { private static final String SOME_MIXED_CHARS = "abc421#¤åäö(/&€"; private static final String SOME_LATIN_1_CHARS = "abcdefghijklmnopqrstuvwxyz"; @Test public void bitPackingOfLengthyArrays() throws Exception { long arrayRecordsBefore = dynamicArrayRecordsInUse(); // Store an int array which would w/o packing require two dynamic records // 4*40 = 160B (assuming data size of 120B) int[] arrayWhichUnpackedWouldFillTwoDynamicRecords = new int[40]; for ( int i = 0; i < arrayWhichUnpackedWouldFillTwoDynamicRecords.length; i++ ) { arrayWhichUnpackedWouldFillTwoDynamicRecords[i] = i*i; } Node node = getGraphDb().createNode(); String key = "the array"; node.setProperty( key, arrayWhichUnpackedWouldFillTwoDynamicRecords ); newTransaction(); // Make sure it only requires one dynamic record assertEquals( arrayRecordsBefore+1, dynamicArrayRecordsInUse() ); clearCache(); assertTrue( Arrays.equals( arrayWhichUnpackedWouldFillTwoDynamicRecords, (int[]) node.getProperty( key ) ) ); } // Tests for strings, although the test class name suggests otherwise @Test public void makeSureLongLatin1StringUsesOneBytePerChar() throws Exception { String string = stringOfLength( SOME_LATIN_1_CHARS, DEFAULT_DATA_BLOCK_SIZE*2-1 ); makeSureRightAmountOfDynamicRecordsUsed( string, 2, STRING_RECORD_COUNTER ); } @Test public void makeSureLongUtf8StringUsesLessThanTwoBytesPerChar() throws Exception { String string = stringOfLength( SOME_MIXED_CHARS, DEFAULT_DATA_BLOCK_SIZE+10 ); makeSureRightAmountOfDynamicRecordsUsed( string, 2, STRING_RECORD_COUNTER ); } @Test public void makeSureLongLatin1StringArrayUsesOneBytePerChar() throws Exception { // Exactly 120 bytes: 5b header + (19+4)*5. w/o compression 5+(19*2 + 4)*5 String[] stringArray = new String[5]; for ( int i = 0; i < stringArray.length; i++ ) stringArray[i] = stringOfLength( SOME_LATIN_1_CHARS, 19 ); makeSureRightAmountOfDynamicRecordsUsed( stringArray, 1, ARRAY_RECORD_COUNTER ); } @Test public void makeSureLongUtf8StringArrayUsesLessThanTwoBytePerChar() throws Exception { String[] stringArray = new String[7]; for ( int i = 0; i < stringArray.length; i++ ) stringArray[i] = stringOfLength( SOME_MIXED_CHARS, 20 ); makeSureRightAmountOfDynamicRecordsUsed( stringArray, 2, ARRAY_RECORD_COUNTER ); } private void makeSureRightAmountOfDynamicRecordsUsed( Object value, int expectedAddedDynamicRecords, DynamicRecordCounter recordCounter ) throws Exception { long stringRecordsBefore = recordCounter.count(); Node node = getGraphDb().createNode(); node.setProperty( "name", value ); newTransaction(); long stringRecordsAfter = recordCounter.count(); assertEquals( stringRecordsBefore+expectedAddedDynamicRecords, stringRecordsAfter ); } private String stringOfLength( String possibilities, int length ) { StringBuilder builder = new StringBuilder(); for ( int i = 0; i < length; i++ ) { builder.append( possibilities.charAt( i%possibilities.length() ) ); } return builder.toString(); } private interface DynamicRecordCounter { long count(); } private class ArrayRecordCounter implements DynamicRecordCounter { @Override public long count() { return dynamicArrayRecordsInUse(); } } private class StringRecordCounter implements DynamicRecordCounter { @Override public long count() { return dynamicStringRecordsInUse(); } } private final DynamicRecordCounter ARRAY_RECORD_COUNTER = new ArrayRecordCounter(); private final DynamicRecordCounter STRING_RECORD_COUNTER = new StringRecordCounter(); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLengthyArrayPacking.java
868
public class TestJumpingIdGenerator { @Test public void testIt() throws Exception { int sizePerJump = 1000; IdGeneratorFactory factory = new JumpingIdGeneratorFactory( sizePerJump ); IdGenerator generator = factory.get( IdType.NODE ); for ( int i = 0; i < sizePerJump/2; i++ ) { assertEquals( i, generator.nextId() ); } for ( int i = 0; i < sizePerJump-1; i++ ) { long expected = 0x100000000L-sizePerJump/2+i; if ( expected >= 0xFFFFFFFFL ) { expected++; } assertEquals( expected, generator.nextId() ); } for ( int i = 0; i < sizePerJump; i++ ) { assertEquals( 0x200000000L-sizePerJump/2+i, generator.nextId() ); } for ( int i = 0; i < sizePerJump; i++ ) { assertEquals( 0x300000000L-sizePerJump/2+i, generator.nextId() ); } } @Test public void testOffsettedFileChannel() throws Exception { File fileName = new File("target/var/neostore.nodestore.db"); JumpingFileSystemAbstraction offsettedFileSystem = new JumpingFileSystemAbstraction( 10 ); offsettedFileSystem.deleteFile( fileName ); offsettedFileSystem.mkdirs( fileName.getParentFile() ); IdGenerator idGenerator = new JumpingIdGeneratorFactory( 10 ).get( IdType.NODE ); JumpingFileChannel channel = (JumpingFileChannel) offsettedFileSystem.open( fileName, "rw" ); for ( int i = 0; i < 16; i++ ) { writeSomethingLikeNodeRecord( channel, idGenerator.nextId(), i ); } channel.close(); channel = (JumpingFileChannel) offsettedFileSystem.open( fileName, "rw" ); idGenerator = new JumpingIdGeneratorFactory( 10 ).get( IdType.NODE ); for ( int i = 0; i < 16; i++ ) { assertEquals( i, readSomethingLikeNodeRecord( channel, idGenerator.nextId() ) ); } channel.close(); offsettedFileSystem.shutdown(); } private byte readSomethingLikeNodeRecord( JumpingFileChannel channel, long id ) throws IOException { ByteBuffer buffer = ByteBuffer.allocate( RECORD_SIZE ); channel.position( id*RECORD_SIZE ); channel.read( buffer ); buffer.flip(); buffer.getLong(); return buffer.get(); } private void writeSomethingLikeNodeRecord( JumpingFileChannel channel, long id, int justAByte ) throws IOException { channel.position( id*RECORD_SIZE ); ByteBuffer buffer = ByteBuffer.allocate( RECORD_SIZE ); buffer.putLong( 4321 ); buffer.put( (byte) justAByte ); buffer.flip(); channel.write( buffer ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestJumpingIdGenerator.java
869
private static class DataChecker2 implements Runnable { private final int count; private final AtomicBoolean done; private final GraphDatabaseService database; protected Transaction tx; public DataChecker2( int count, AtomicBoolean done, GraphDatabaseService database ) { this.count = count; this.done = done; this.database = database; } @Override public void run() { System.out.println( "Start checking data" ); int totalDiff = 0; while(!done.get()) { try { int correctValue = -1; int diff = 0; tx = database.beginTx(); for (int i = 0; i < count; i++) { int foo = getNodeValue( i ); if (correctValue == -1) correctValue = foo; diff = diff + foo - correctValue; } totalDiff += diff; tx.success(); } catch( Exception e ) { e.printStackTrace(); tx.failure(); } finally { tx.finish(); } } System.out.printf( "Done checking data, %d diff\n", totalDiff ); } protected int getNodeValue( int i ) { Node node = database.getNodeById( i+1 ); return (Integer) node.getProperty( "foo" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
870
private static class DataChecker implements Runnable { private final AtomicBoolean done; private final GraphDatabaseService database; protected Transaction tx; public DataChecker( AtomicBoolean done, GraphDatabaseService database ) { this.done = done; this.database = database; } @Override public void run() { System.out.println( "Start checking data" ); double errors = 0; double total = 0; while(!done.get()) { try { tx = database.beginTx(); int firstNode = getFirstValue(); int lastNode = getSecondValue(); if (firstNode - lastNode != 0) { errors++; } total++; tx.success(); } finally { tx.finish(); } } double percentage = (errors/total)*100.0; System.out.printf( "Done checking data, %1.0f errors found(%1.3f%%)\n", errors, percentage ); } protected Integer getSecondValue() { return (Integer) database.getNodeById( 1000 ).getProperty( "foo" ); } protected Integer getFirstValue() { return (Integer) database.getNodeById( 1 ).getProperty( "foo" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
871
private static class DataChanger implements Callable { private final GraphDatabaseService database; private final int count; private final AtomicBoolean done; public DataChanger( GraphDatabaseService database, int count, AtomicBoolean done ) { this.database = database; this.count = count; this.done = done; } @Override public Object call() throws Exception { System.out.println( "Start changing data" ); int totalDeadlocks = 0; try { for (int round = 0; round < 100; round++) { int deadLocks = 0; DeadlockDetectedException ex = null; do { ex = null; Transaction tx = database.beginTx(); try { for (int i = 0; i < count; i++) { Node node = database.getNodeById( i+1 ); int foo = (Integer) node.getProperty( "foo" ); node.setProperty( "foo", foo+1 ); } tx.success(); } catch( DeadlockDetectedException e ) { System.out.println("Deadlock detected"); deadLocks = deadLocks+1; ex = e; tx.failure(); if (deadLocks > 100) { totalDeadlocks += deadLocks; throw e; } } finally { tx.finish(); } } while (ex != null); totalDeadlocks += deadLocks; } } catch( Exception e ) { e.printStackTrace(); throw e; } finally { done.set( true ); System.out.printf( "Done changing data. Detected %d deadlocks\n", totalDeadlocks ); } return null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
872
{ @Override protected int getNodeValue( int i ) { Node node = database.getNodeById( 1000-i ); this.tx.acquireReadLock( node ); return (Integer) node.getProperty( "foo" ); } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
873
{ @Override protected int getNodeValue( int i ) { Node node = database.getNodeById( i+1 ); this.tx.acquireReadLock( node ); return (Integer) node.getProperty( "foo" ); } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
874
{ @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1000 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
875
{ @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1000 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
876
{ @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1000 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
877
{ @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1000 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
878
@Ignore( "unstable" ) public class TestIsolationMultipleThreads { GraphDatabaseService database; private static final int COUNT = 1000; @Before public void setup() { database = new TestGraphDatabaseFactory().newImpermanentDatabase(); Transaction tx = database.beginTx(); for (int i = 0; i < COUNT; i++) { Node node = database.createNode(); node.setProperty( "foo", 0 ); } tx.success(); tx.finish(); } @After public void tearDown() { database.shutdown(); } /** * This test shows what happens with no isolation, i.e. default usage of Neo4j. One thread updates * a property "foo" on 1000 nodes by increasing it by 1 in each round. Another thread reads the * first and last node and computes the difference. With perfect isolation the result should be 0. * * Here the result is that roughly 5% of the time the result is not 0, since the reading thread will * see changes from the other thread midway through its calculation. * * @throws Exception */ @Test public void testIsolation() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 1 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker( done, database ) ); new DataChanger( database, COUNT, done ).call(); } /** * * This test does the same thing, but acquires read locks on BOTH nodes before reading the value. * This ensures that it will wait for the write transaction to finish, and so no errors are detected. * * @throws Exception */ @Test public void testIsolationWithLocks() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 2 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker( done, database ) { @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1000 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } }); new DataChanger( database, COUNT, done ).call(); } /** * This test does the same thing as the previous one, but acquires the nodes * in the reverse order. The result is a consistent deadlock for the writer, which * is unable to proceed, even with deadlock handling and retries. * * @throws Exception */ @Test(expected = DeadlockDetectedException.class) public void testIsolationWithLocksReversed() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 2 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker( done, database ) { @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1000 ); this.tx.acquireReadLock( nodeById ); return (Integer) nodeById.getProperty( "foo" ); } }); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } /** * * This test does the same thing, but acquires read locks on BOTH nodes before reading the value. * The locks are released after reading the value. * * This gives 0% errors in my tests. * * @throws Exception */ @Test public void testIsolationWithShortLocks() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 1 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker( done, database ) { @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1000 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } }); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } /** * * This test does the same thing, but acquires read locks on BOTH nodes before reading the value, in reverse. * The locks are released after reading the value. * * This gives roughly 60-90%+ errors in my tests. * * @throws Exception */ @Test public void testIsolationWithShortLocksReversed() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 2 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker( done, database ) { @Override protected Integer getSecondValue() { Node nodeById = database.getNodeById( 1 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } @Override protected Integer getFirstValue() { Node nodeById = database.getNodeById( 1000 ); Lock lock = this.tx.acquireReadLock( nodeById ); try { return (Integer) nodeById.getProperty( "foo" ); } finally { lock.release(); } } }); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } /** * This test shows what happens with no isolation, i.e. default usage of Neo4j. One thread updates * a property "foo" on 1000 nodes by increasing it by 1 in each round. Another thread reads the * property on all nodes and computes the total difference from expected value. With perfect isolation the result should be 0. * * This will always yield a result different from 0. * * @throws Exception */ @Test public void testIsolationAll() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 1 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker2( COUNT, done, database ) ); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } /** * This test does the same as above, but now read locks nodes before calculating the diff. * * This will always yield a result of 0, i.e. correct. * * @throws Exception */ @Test public void testIsolationAllWithLocks() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 1 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker2( COUNT, done, database ) { @Override protected int getNodeValue( int i ) { Node node = database.getNodeById( i+1 ); this.tx.acquireReadLock( node ); return (Integer) node.getProperty( "foo" ); } }); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } /** * This test does the same as above, but now locks the nodes in the opposite order. * * This will always yield a DeadlockDetectedException. Retries does not help. * * @throws Exception */ @Test(expected = DeadlockDetectedException.class) public void testIsolationAllWithLocksReverse() throws Exception { ExecutorService executor = Executors.newFixedThreadPool( 1 ); final AtomicBoolean done = new AtomicBoolean( false ); executor.submit( new DataChecker2( COUNT, done, database ) { @Override protected int getNodeValue( int i ) { Node node = database.getNodeById( 1000-i ); this.tx.acquireReadLock( node ); return (Integer) node.getProperty( "foo" ); } }); new DataChanger( database, COUNT, done ).call(); executor.shutdownNow(); } private static class DataChanger implements Callable { private final GraphDatabaseService database; private final int count; private final AtomicBoolean done; public DataChanger( GraphDatabaseService database, int count, AtomicBoolean done ) { this.database = database; this.count = count; this.done = done; } @Override public Object call() throws Exception { System.out.println( "Start changing data" ); int totalDeadlocks = 0; try { for (int round = 0; round < 100; round++) { int deadLocks = 0; DeadlockDetectedException ex = null; do { ex = null; Transaction tx = database.beginTx(); try { for (int i = 0; i < count; i++) { Node node = database.getNodeById( i+1 ); int foo = (Integer) node.getProperty( "foo" ); node.setProperty( "foo", foo+1 ); } tx.success(); } catch( DeadlockDetectedException e ) { System.out.println("Deadlock detected"); deadLocks = deadLocks+1; ex = e; tx.failure(); if (deadLocks > 100) { totalDeadlocks += deadLocks; throw e; } } finally { tx.finish(); } } while (ex != null); totalDeadlocks += deadLocks; } } catch( Exception e ) { e.printStackTrace(); throw e; } finally { done.set( true ); System.out.printf( "Done changing data. Detected %d deadlocks\n", totalDeadlocks ); } return null; } } private static class DataChecker implements Runnable { private final AtomicBoolean done; private final GraphDatabaseService database; protected Transaction tx; public DataChecker( AtomicBoolean done, GraphDatabaseService database ) { this.done = done; this.database = database; } @Override public void run() { System.out.println( "Start checking data" ); double errors = 0; double total = 0; while(!done.get()) { try { tx = database.beginTx(); int firstNode = getFirstValue(); int lastNode = getSecondValue(); if (firstNode - lastNode != 0) { errors++; } total++; tx.success(); } finally { tx.finish(); } } double percentage = (errors/total)*100.0; System.out.printf( "Done checking data, %1.0f errors found(%1.3f%%)\n", errors, percentage ); } protected Integer getSecondValue() { return (Integer) database.getNodeById( 1000 ).getProperty( "foo" ); } protected Integer getFirstValue() { return (Integer) database.getNodeById( 1 ).getProperty( "foo" ); } } private static class DataChecker2 implements Runnable { private final int count; private final AtomicBoolean done; private final GraphDatabaseService database; protected Transaction tx; public DataChecker2( int count, AtomicBoolean done, GraphDatabaseService database ) { this.count = count; this.done = done; this.database = database; } @Override public void run() { System.out.println( "Start checking data" ); int totalDiff = 0; while(!done.get()) { try { int correctValue = -1; int diff = 0; tx = database.beginTx(); for (int i = 0; i < count; i++) { int foo = getNodeValue( i ); if (correctValue == -1) correctValue = foo; diff = diff + foo - correctValue; } totalDiff += diff; tx.success(); } catch( Exception e ) { e.printStackTrace(); tx.failure(); } finally { tx.finish(); } } System.out.printf( "Done checking data, %d diff\n", totalDiff ); } protected int getNodeValue( int i ) { Node node = database.getNodeById( i+1 ); return (Integer) node.getProperty( "foo" ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationMultipleThreads.java
879
{ public void run() { Transaction tx = getGraphDb().beginTx(); try { node1.setProperty( "key", "new" ); rel1.setProperty( "key", "new" ); node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "TEST" ) ); assertPropertyEqual( node1, "key", "new" ); assertPropertyEqual( rel1, "key", "new" ); assertRelationshipCount( node1, 2 ); assertRelationshipCount( node2, 2 ); latch1.countDown(); latch2.await(); assertPropertyEqual( node1, "key", "new" ); assertPropertyEqual( rel1, "key", "new" ); assertRelationshipCount( node1, 2 ); assertRelationshipCount( node2, 2 ); // no tx.success(); } catch ( InterruptedException e ) { e.printStackTrace(); Thread.interrupted(); } finally { tx.finish(); assertPropertyEqual( node1, "key", "old" ); assertPropertyEqual( rel1, "key", "old" ); assertRelationshipCount( node1, 1 ); assertRelationshipCount( node2, 1 ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationBasic.java
880
public class TestIsolationBasic extends AbstractNeo4jTestCase { /* * Tests that changes performed in a transaction before commit are not apparent in another. */ @Test public void testSimpleTransactionIsolation() throws InterruptedException { // Start setup - create base data commit(); final CountDownLatch latch1 = new CountDownLatch( 1 ); final CountDownLatch latch2 = new CountDownLatch( 1 ); Transaction tx = getGraphDb().beginTx(); Node n1, n2; Relationship r1; try { n1 = getGraphDb().createNode(); n2 = getGraphDb().createNode(); r1 = n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "TEST" ) ); tx.success(); } finally { tx.finish(); } final Node node1 = n1; final Node node2 = n2; final Relationship rel1 = r1; tx = getGraphDb().beginTx(); try { node1.setProperty( "key", "old" ); rel1.setProperty( "key", "old" ); tx.success(); } finally { tx.finish(); } assertPropertyEqual( node1, "key", "old" ); assertPropertyEqual( rel1, "key", "old" ); assertRelationshipCount( node1, 1 ); assertRelationshipCount( node2, 1 ); // This is the mutating transaction - it will change stuff which will be read in between Thread t1 = new Thread( new Runnable() { public void run() { Transaction tx = getGraphDb().beginTx(); try { node1.setProperty( "key", "new" ); rel1.setProperty( "key", "new" ); node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "TEST" ) ); assertPropertyEqual( node1, "key", "new" ); assertPropertyEqual( rel1, "key", "new" ); assertRelationshipCount( node1, 2 ); assertRelationshipCount( node2, 2 ); latch1.countDown(); latch2.await(); assertPropertyEqual( node1, "key", "new" ); assertPropertyEqual( rel1, "key", "new" ); assertRelationshipCount( node1, 2 ); assertRelationshipCount( node2, 2 ); // no tx.success(); } catch ( InterruptedException e ) { e.printStackTrace(); Thread.interrupted(); } finally { tx.finish(); assertPropertyEqual( node1, "key", "old" ); assertPropertyEqual( rel1, "key", "old" ); assertRelationshipCount( node1, 1 ); assertRelationshipCount( node2, 1 ); } } } ); t1.start(); latch1.await(); // The transaction started above that runs in t1 has not finished. The old values should still be visible. assertPropertyEqual( node1, "key", "old" ); assertPropertyEqual( rel1, "key", "old" ); assertRelationshipCount( node1, 1 ); assertRelationshipCount( node2, 1 ); latch2.countDown(); t1.join(); // The transaction in t1 has finished but not committed. Its changes should still not be visible. assertPropertyEqual( node1, "key", "old" ); assertPropertyEqual( rel1, "key", "old" ); assertRelationshipCount( node1, 1 ); assertRelationshipCount( node2, 1 ); tx = getGraphDb().beginTx(); try { for ( Relationship rel : node1.getRelationships() ) { rel.delete(); } node1.delete(); node2.delete(); tx.success(); } finally { tx.finish(); } } private void assertPropertyEqual( PropertyContainer primitive, String key, String value ) { Transaction tx = getGraphDb().beginTx(); try { assertEquals( value, primitive.getProperty( key ) ); } finally { tx.finish(); } } private void assertRelationshipCount( Node node, int count ) { Transaction tx = getGraphDb().beginTx(); try { int actualCount = 0; for ( Relationship rel : node.getRelationships() ) { actualCount++; } assertEquals( count, actualCount ); } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIsolationBasic.java
881
public class TestIdReuse { @Test public void makeSureIdsGetsReusedForPropertyStore() throws Exception { makeSureIdsGetsReused( "neostore.propertystore.db", 10, 200 ); } @Test public void makeSureIdsGetsReusedForArrayStore() throws Exception { long[] array = new long[500]; for ( int i = 0; i < array.length; i++ ) { array[i] = 0xFFFFFFFFFFFFL + i; } makeSureIdsGetsReused( "neostore.propertystore.db.arrays", array, 20 ); } @Test public void makeSureIdsGetsReusedForStringStore() throws Exception { String string = "something"; for ( int i = 0; i < 100; i++ ) { string += "something else " + i; } makeSureIdsGetsReused( "neostore.propertystore.db.strings", string, 20 ); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private void makeSureIdsGetsReused( String fileName, Object value, int iterations ) throws Exception { File storeDir = new File( "target/var/idreuse" ); File file = new File( storeDir, fileName ); GraphDatabaseService db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ). newImpermanentDatabaseBuilder( storeDir.getPath() ). setConfig( GraphDatabaseSettings.use_memory_mapped_buffers, Settings.FALSE ). newGraphDatabase(); for ( int i = 0; i < 5; i++ ) { setAndRemoveSomeProperties( db, value ); } db.shutdown(); long sizeBefore = file.length(); db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase( storeDir.getPath() ); for ( int i = 0; i < iterations; i++ ) { setAndRemoveSomeProperties( db, value ); } db.shutdown(); assertEquals( sizeBefore, file.length() ); } private void setAndRemoveSomeProperties( GraphDatabaseService graphDatabaseService, Object value ) { Transaction tx = graphDatabaseService.beginTx(); Node commonNode = graphDatabaseService.createNode(); try { for ( int i = 0; i < 10; i++ ) { commonNode.setProperty( "key" + i, value ); } tx.success(); } finally { tx.finish(); } tx = graphDatabaseService.beginTx(); try { for ( int i = 0; i < 10; i++ ) { commonNode.removeProperty( "key" + i ); } tx.success(); } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestIdReuse.java
882
public class TestExceptionTypeOnInvalidIds { private static final long SMALL_POSSITIVE_INTEGER = 5; private static final long SMALL_NEGATIVE_INTEGER = -5; private static final long BIG_POSSITIVE_INTEGER = Integer.MAX_VALUE; private static final long BIG_NEGATIVE_INTEGER = Integer.MIN_VALUE; private static final long SMALL_POSSITIVE_LONG = ((long) Integer.MAX_VALUE) + 1; private static final long SMALL_NEGATIVE_LONG = -((long) Integer.MIN_VALUE) - 1; private static final long BIG_POSSITIVE_LONG = Long.MAX_VALUE; private static final long BIG_NEGATIVE_LONG = Long.MIN_VALUE; private static GraphDatabaseService graphdb; private static GraphDatabaseService graphDbReadOnly; private Transaction tx; @BeforeClass public static void createDatabase() { graphdb = new GraphDatabaseFactory().newEmbeddedDatabase( getRandomStoreDir() ); String storeDir = getRandomStoreDir(); new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ).shutdown(); graphDbReadOnly = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( storeDir ). setConfig( GraphDatabaseSettings.read_only, TRUE ). newGraphDatabase(); } private static String getRandomStoreDir() { return "target/var/id_test/" + UUID.randomUUID(); } @AfterClass public static void destroyDatabase() { graphDbReadOnly.shutdown(); graphDbReadOnly = null; graphdb.shutdown(); graphdb = null; } @Before public void startTransaction() { tx = graphdb.beginTx(); } @After public void endTransaction() { tx.finish(); tx = null; } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getNodeBySmallPossitiveInteger() throws Exception { getNodeById( SMALL_POSSITIVE_INTEGER ); getNodeByIdReadOnly( SMALL_POSSITIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getNodeBySmallNegativeInteger() throws Exception { getNodeById( SMALL_NEGATIVE_INTEGER ); getNodeByIdReadOnly( SMALL_NEGATIVE_INTEGER ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getNodeByBigPossitiveInteger() throws Exception { getNodeById( BIG_POSSITIVE_INTEGER ); getNodeByIdReadOnly( BIG_POSSITIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getNodeByBigNegativeInteger() throws Exception { getNodeById( BIG_NEGATIVE_INTEGER ); getNodeByIdReadOnly( BIG_NEGATIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getNodeBySmallPossitiveLong() throws Exception { getNodeById( SMALL_POSSITIVE_LONG ); getNodeByIdReadOnly( SMALL_POSSITIVE_LONG ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getNodeBySmallNegativeLong() throws Exception { getNodeById( SMALL_NEGATIVE_LONG ); getNodeByIdReadOnly( SMALL_NEGATIVE_LONG ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getNodeByBigPossitiveLong() throws Exception { getNodeById( BIG_POSSITIVE_LONG ); getNodeByIdReadOnly( BIG_POSSITIVE_LONG ); } /* finds the node with id=0, since that what the id truncates to */ @Test( expected = NotFoundException.class ) public void getNodeByBigNegativeLong() throws Exception { getNodeById( BIG_NEGATIVE_LONG ); getNodeByIdReadOnly( BIG_NEGATIVE_LONG ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getRelationshipBySmallPossitiveInteger() throws Exception { getRelationshipById( SMALL_POSSITIVE_INTEGER ); getRelationshipByIdReadOnly( SMALL_POSSITIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getRelationshipBySmallNegativeInteger() throws Exception { getRelationshipById( SMALL_NEGATIVE_INTEGER ); getRelationshipByIdReadOnly( SMALL_POSSITIVE_INTEGER ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getRelationshipByBigPossitiveInteger() throws Exception { getRelationshipById( BIG_POSSITIVE_INTEGER ); getRelationshipByIdReadOnly( BIG_POSSITIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getRelationshipByBigNegativeInteger() throws Exception { getRelationshipById( BIG_NEGATIVE_INTEGER ); getRelationshipByIdReadOnly( BIG_NEGATIVE_INTEGER ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getRelationshipBySmallPossitiveLong() throws Exception { getRelationshipById( SMALL_POSSITIVE_LONG ); getRelationshipByIdReadOnly( SMALL_POSSITIVE_LONG ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getRelationshipBySmallNegativeLong() throws Exception { getRelationshipById( SMALL_NEGATIVE_LONG ); getRelationshipByIdReadOnly( SMALL_NEGATIVE_LONG ); } /* throws IllegalArgumentException instead of NotFoundException */ @Test( expected = NotFoundException.class ) public void getRelationshipByBigPossitiveLong() throws Exception { getRelationshipById( BIG_POSSITIVE_LONG ); getRelationshipByIdReadOnly( BIG_POSSITIVE_LONG ); } /* behaves as expected */ @Test( expected = NotFoundException.class ) public void getRelationshipByBigNegativeLong() throws Exception { getRelationshipById( BIG_NEGATIVE_LONG ); getRelationshipByIdReadOnly( BIG_NEGATIVE_LONG ); } private void getNodeById( long index ) { Node value = graphdb.getNodeById( index ); fail( String.format( "Returned Node [0x%x] for index 0x%x (int value: 0x%x)", value.getId(), index, (int) index ) ); } private void getNodeByIdReadOnly( long index ) { Node value = graphDbReadOnly.getNodeById( index ); fail( String.format( "Returned Node [0x%x] for index 0x%x (int value: 0x%x)", value.getId(), index, (int) index ) ); } private void getRelationshipById( long index ) { Relationship value = graphdb.getRelationshipById( index ); fail( String.format( "Returned Relationship [0x%x] for index 0x%x (int value: 0x%x)", value.getId(), index, (int) index ) ); } private void getRelationshipByIdReadOnly( long index ) { Relationship value = graphDbReadOnly.getRelationshipById( index ); fail( String.format( "Returned Relationship [0x%x] for index 0x%x (int value: 0x%x)", value.getId(), index, (int) index ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestExceptionTypeOnInvalidIds.java
883
public class TestCrashWithRebuildSlow { @Test public void crashAndRebuildSlowWithDynamicStringDeletions() throws Exception { String storeDir = "dir"; final GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ).newImpermanentDatabase( storeDir ); produceNonCleanDefraggedStringStore( db ); EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( db ) ); // Recover with rebuild_idgenerators_fast=false assertNumberOfFreeIdsEquals( storeDir, snapshot, 0 ); GraphDatabaseAPI newDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot ) .newImpermanentDatabaseBuilder( storeDir ) .setConfig( GraphDatabaseSettings.rebuild_idgenerators_fast, Settings.FALSE ) .newGraphDatabase(); assertNumberOfFreeIdsEquals( storeDir, snapshot, 4 ); Transaction transaction = newDb.beginTx(); try { int nameCount = 0; int relCount = 0; for ( Node node : GlobalGraphOperations.at( newDb ).getAllNodes() ) { nameCount++; assertThat( node, inTx( newDb, hasProperty( "name" ) ) ); relCount += count( node.getRelationships( Direction.OUTGOING ) ); } assertEquals( 16, nameCount ); assertEquals( 12, relCount ); } finally { transaction.finish(); newDb.shutdown(); } } private void assertNumberOfFreeIdsEquals( String storeDir, EphemeralFileSystemAbstraction snapshot, int numberOfFreeIds ) { assertEquals( 9/*header*/ + 8*numberOfFreeIds, snapshot.getFileSize( new File( storeDir, "neostore.propertystore.db.strings.id" ) ) ); } private void produceNonCleanDefraggedStringStore( GraphDatabaseService db ) { // Create some strings List<Node> nodes = new ArrayList<Node>(); Transaction tx = db.beginTx(); try { Node previous = null; for ( int i = 0; i < 20; i++ ) { Node node = db.createNode(); node.setProperty( "name", "a looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string" ); nodes.add( node ); if ( previous != null ) { previous.createRelationshipTo( node, MyRelTypes.TEST ); } previous = node; } tx.success(); } finally { tx.finish(); } // Delete some of them, but leave some in between deletions tx = db.beginTx(); try { delete( nodes.get( 5 ) ); delete( nodes.get( 7 ) ); delete( nodes.get( 8 ) ); delete( nodes.get( 10 ) ); tx.success(); } finally { tx.finish(); } } private static void delete( Node node ) { for ( Relationship rel : node.getRelationships() ) { rel.delete(); } node.delete(); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestCrashWithRebuildSlow.java
884
{ @Override public void run() { awaitStartSignalAndRandomTimeLonger( startSignal ); Transaction transaction = db.beginTx(); try { assertEquals( relCount, count( node.getRelationships() ) ); } catch ( Throwable e ) { errors.add( e ); } finally { transaction.finish(); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentRelationshipChainLoadingIssue.java
885
private class StringRecordCounter implements DynamicRecordCounter { @Override public long count() { return dynamicStringRecordsInUse(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLengthyArrayPacking.java
886
{ public Iterator<boolean[]> iterator() { return new PrefetchingIterator<boolean[]>() { int pos = 0; @Override protected boolean[] fetchNextOrNull() { if ( pos < max ) { int cur = pos++; boolean[] result = new boolean[size]; for ( int i = 0; i < size; i++ ) { result[i] = ( cur & 1 ) == 1; cur >>= 1; } return result; } return null; } }; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLoopRelationships.java
887
{ @Override public NodeImpl loadById( long id ) { NodeRecord record = persistenceManager.loadLightNode( id ); if ( record == null ) { return null; } return new NodeImpl( id ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
888
{ int pos = 0; @Override protected boolean[] fetchNextOrNull() { if ( pos < max ) { int cur = pos++; boolean[] result = new boolean[size]; for ( int i = 0; i < size; i++ ) { result[i] = ( cur & 1 ) == 1; cur >>= 1; } return result; } return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestLoopRelationships.java
889
final Node root = tx( new Callable<Node>() { @Override public Node call() throws Exception { return graphdb.createNode(); } });
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestRaceOnMultipleNodeImpl.java
890
public class TestRaceOnMultipleNodeImpl { @Test public void concurrentRemoveProperty() throws Exception { // ASSUMPTION: locking is fair, first one to wait is first one to get the lock final Node root = tx( new Callable<Node>() { @Override public Node call() throws Exception { return graphdb.createNode(); } }); final Node original = tx( new Callable<Node>() { // setup: create the node with the property that we will remove @Override public Node call() throws Exception { Node node = graphdb.createNode(); node.setProperty( "key", "original" ); return node; } } ); // set up a wait chain: remover <- blocker <- offender final CountDownLatch removerSetUp = latch(), waitChainSetUp = latch(); txThread( "remover", new Runnable() { @Override public void run() { // remove the property then wait until the entire wait chain is set up original.removeProperty( "key" ); removerSetUp.countDown(); await( waitChainSetUp ); } } ); await( removerSetUp ); clearCaches(); // mess things up by giving threads different NodeImpl instances awaitWaitingState( txThread( "blocker", new Runnable() { @Override public void run() { original.removeProperty( "not existing" ); // block to make sure that we wait until "remover" is done root.setProperty( "key", "root" ); // reuse property record with same key for different node } } ) ); clearCaches(); // mess things up by giving threads different NodeImpl instances final AtomicBoolean precondition = new AtomicBoolean( false ); // just used as a mutable Boolean final CountDownLatch readyToBlockOnLock = latch(), done = latch(); Thread offender = thread( "offender", new Runnable() { @Override public void run() { try { tx( new Runnable() { @Override public void run() { // populate the NodeImpl object to make sure that we don't go to disk after acquiring lock precondition.set( "original".equals( original.getProperty( "key" ) ) ); // this prevents false positives in awaitWaitingState( offender ) readyToBlockOnLock.countDown(); // this will block on the lock since there are two other threads ahead of us original.removeProperty( "key" ); } } ); } finally { done.countDown(); } } } ); await( readyToBlockOnLock ); // wait until no other locks are in the way awaitWaitingState( offender ); // wait until "offender" has started waiting on the lock clearCaches(); // clear the caches so that the NodeImpl will not get updated waitChainSetUp.countDown(); // allow the transactions to start await( done ); clearCaches(); // to make sure that we do verification on the persistent state in the db // verify assertThat( root, inTx( graphdb, hasProperty( "key" ) ) ); assertTrue( "invalid precondition", precondition.get() ); } @Test public void concurrentSetProperty() throws Exception { // ASSUMPTION: locking is fair, first one to wait is first one to get the lock final Node root = tx( new Callable<Node>() { @Override public Node call() throws Exception { return graphdb.createNode(); } } ); tx( new Runnable() { @Override public void run() { root.setProperty( "tx", "main" ); root.setProperty( "a", 1 ); root.setProperty( "b", 2 ); root.setProperty( "c", 3 ); root.setProperty( "d", 4 ); } } ); final CountDownLatch writerSetUp = latch(), waitChainSetUp = latch(); txThread( "writer", new Runnable() { @Override public void run() { root.setProperty( "e", 5 ); writerSetUp.countDown(); await( waitChainSetUp ); root.setProperty( "tx", "writer" ); } } ); await( writerSetUp ); awaitWaitingState( txThread( "remover", new Runnable() { @Override public void run() { root.removeProperty( "tx" ); } } ) ); clearCaches(); final AtomicBoolean precondition = new AtomicBoolean( false ); // just used as a mutable Boolean final CountDownLatch offenderSetUp = latch(), done = latch(); Thread offender = thread( "offender", new Runnable() { @Override public void run() { try { tx( new Runnable() { @Override public void run() { for ( @SuppressWarnings("unused")String key : root.getPropertyKeys() ) precondition.set( true ); offenderSetUp.countDown(); root.setProperty( "tx", "offender" ); } } ); } finally { done.countDown(); } } } ); await( offenderSetUp ); awaitWaitingState( offender ); clearCaches(); waitChainSetUp.countDown(); await( done ); clearCaches(); assertThat( root, inTx( graphdb, hasProperty( "tx" ).withValue( "offender" ) ) ); assertTrue( "node should not have any properties when entering second tx", precondition.get() ); } private CountDownLatch latch() { return new CountDownLatch( 1 ); } private static void await( CountDownLatch latch ) { for ( ;; ) try { latch.await(); return; } catch ( InterruptedException e ) { // ignore } } private void clearCaches() { graphdb.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); } private static Thread thread( String name, Runnable task ) { Thread thread = new Thread( task, name ); thread.start(); return thread; } private static void awaitWaitingState( Thread thread ) { for ( ;/*ever*/; ) switch ( thread.getState() ) { case WAITING: case TIMED_WAITING: return; case TERMINATED: throw new IllegalStateException( "thread terminated" ); default: try { Thread.sleep( 1 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } } private Thread txThread(String name, final Runnable task) { return thread( name, new Runnable() { @Override public void run() { tx( task ); } } ); } private void tx( Runnable task ) { Transaction tx = graphdb.beginTx(); try { task.run(); tx.success(); } finally { tx.finish(); } } private <R> R tx( Callable<R> task ) throws Exception { Transaction tx = graphdb.beginTx(); try { R result = task.call(); tx.success(); return result; } finally { tx.finish(); } } private GraphDatabaseAPI graphdb; @Before public void startDb() { graphdb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase(); } @After public void shutdownDb() { try { if ( graphdb != null ) graphdb.shutdown(); } finally { graphdb = null; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestRaceOnMultipleNodeImpl.java
891
public class TestPropertyTypes extends AbstractNeo4jTestCase { private Node node1 = null; @Before public void createInitialNode() { node1 = getGraphDb().createNode(); } @After public void deleteInitialNode() { node1.delete(); } @Test public void testDoubleType() { Double dValue = new Double( 45.678d ); String key = "testdouble"; node1.setProperty( key, dValue ); newTransaction(); clearCache(); Double propertyValue = null; propertyValue = (Double) node1.getProperty( key ); assertEquals( dValue, propertyValue ); dValue = new Double( 56784.3243d ); node1.setProperty( key, dValue ); newTransaction(); clearCache(); propertyValue = (Double) node1.getProperty( key ); assertEquals( dValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testFloatType() { Float fValue = new Float( 45.678f ); String key = "testfloat"; node1.setProperty( key, fValue ); newTransaction(); clearCache(); Float propertyValue = null; propertyValue = (Float) node1.getProperty( key ); assertEquals( fValue, propertyValue ); fValue = new Float( 5684.3243f ); node1.setProperty( key, fValue ); newTransaction(); clearCache(); propertyValue = (Float) node1.getProperty( key ); assertEquals( fValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testLongType() { long time = System.currentTimeMillis(); Long lValue = new Long( time ); String key = "testlong"; node1.setProperty( key, lValue ); newTransaction(); clearCache(); Long propertyValue = null; propertyValue = (Long) node1.getProperty( key ); assertEquals( lValue, propertyValue ); lValue = new Long( System.currentTimeMillis() ); node1.setProperty( key, lValue ); newTransaction(); clearCache(); propertyValue = (Long) node1.getProperty( key ); assertEquals( lValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); node1.setProperty( "other", 123L ); assertEquals( 123L, node1.getProperty( "other" ) ); newTransaction(); clearCache(); assertEquals( 123L, node1.getProperty( "other" ) ); } @Test public void testIntType() { int time = (int)System.currentTimeMillis(); Integer iValue = new Integer( time ); String key = "testing"; node1.setProperty( key, iValue ); newTransaction(); clearCache(); Integer propertyValue = null; propertyValue = (Integer) node1.getProperty( key ); assertEquals( iValue, propertyValue ); iValue = new Integer( (int)System.currentTimeMillis() ); node1.setProperty( key, iValue ); newTransaction(); clearCache(); propertyValue = (Integer) node1.getProperty( key ); assertEquals( iValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); node1.setProperty( "other", 123L ); assertEquals( 123L, node1.getProperty( "other" ) ); newTransaction(); clearCache(); assertEquals( 123L, node1.getProperty( "other" ) ); } @Test public void testByteType() { byte b = (byte) 177; Byte bValue = new Byte( b ); String key = "testbyte"; node1.setProperty( key, bValue ); newTransaction(); clearCache(); Byte propertyValue = null; propertyValue = (Byte) node1.getProperty( key ); assertEquals( bValue, propertyValue ); bValue = new Byte( (byte) 200 ); node1.setProperty( key, bValue ); newTransaction(); clearCache(); propertyValue = (Byte) node1.getProperty( key ); assertEquals( bValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testShortType() { short value = 453; Short sValue = new Short( value ); String key = "testshort"; node1.setProperty( key, sValue ); newTransaction(); clearCache(); Short propertyValue = null; propertyValue = (Short) node1.getProperty( key ); assertEquals( sValue, propertyValue ); sValue = new Short( (short) 5335 ); node1.setProperty( key, sValue ); newTransaction(); clearCache(); propertyValue = (Short) node1.getProperty( key ); assertEquals( sValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testCharType() { char c = 'c'; Character cValue = new Character( c ); String key = "testchar"; node1.setProperty( key, cValue ); newTransaction(); clearCache(); Character propertyValue = null; propertyValue = (Character) node1.getProperty( key ); assertEquals( cValue, propertyValue ); cValue = new Character( 'd' ); node1.setProperty( key, cValue ); newTransaction(); clearCache(); propertyValue = (Character) node1.getProperty( key ); assertEquals( cValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testBooleanType() { boolean value = true; Boolean bValue = new Boolean( value ); String key = "testbool"; node1.setProperty( key, bValue ); newTransaction(); clearCache(); Boolean propertyValue = null; propertyValue = (Boolean) node1.getProperty( key ); assertEquals( bValue, propertyValue ); bValue = new Boolean( false ); node1.setProperty( key, bValue ); newTransaction(); clearCache(); propertyValue = (Boolean) node1.getProperty( key ); assertEquals( bValue, propertyValue ); node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testIntArray() { int[] array1 = new int[] { 1, 2, 3, 4, 5 }; Integer[] array2 = new Integer[] { 6, 7, 8 }; String key = "testintarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); int propertyValue[] = null; propertyValue = (int[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (int[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Integer( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testShortArray() { short[] array1 = new short[] { 1, 2, 3, 4, 5 }; Short[] array2 = new Short[] { 6, 7, 8 }; String key = "testintarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); short propertyValue[] = null; propertyValue = (short[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (short[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Short( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testStringArray() { String[] array1 = new String[] { "a", "b", "c", "d", "e" }; String[] array2 = new String[] { "ff", "gg", "hh" }; String key = "teststringarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); String propertyValue[] = null; propertyValue = (String[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (String[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], propertyValue[i] ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testBooleanArray() { boolean[] array1 = new boolean[] { true, false, true, false, true }; Boolean[] array2 = new Boolean[] { false, true, false }; String key = "testboolarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); boolean propertyValue[] = null; propertyValue = (boolean[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (boolean[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Boolean( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testDoubleArray() { double[] array1 = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; Double[] array2 = new Double[] { 6.0, 7.0, 8.0 }; String key = "testdoublearray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); double propertyValue[] = null; propertyValue = (double[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i], 0.0 ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (double[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Double( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testFloatArray() { float[] array1 = new float[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; Float[] array2 = new Float[] { 6.0f, 7.0f, 8.0f }; String key = "testfloatarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); float propertyValue[] = null; propertyValue = (float[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i], 0.0 ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (float[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Float( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testLongArray() { long[] array1 = new long[] { 1, 2, 3, 4, 5 }; Long[] array2 = new Long[] { 6l, 7l, 8l }; String key = "testlongarray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); long[] propertyValue = null; propertyValue = (long[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (long[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Long( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testByteArray() { byte[] array1 = new byte[] { 1, 2, 3, 4, 5 }; Byte[] array2 = new Byte[] { 6, 7, 8 }; String key = "testbytearray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); byte[] propertyValue = null; propertyValue = (byte[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (byte[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Byte( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testCharArray() { char[] array1 = new char[] { '1', '2', '3', '4', '5' }; Character[] array2 = new Character[] { '6', '7', '8' }; String key = "testchararray"; node1.setProperty( key, array1 ); newTransaction(); clearCache(); char[] propertyValue = null; propertyValue = (char[]) node1.getProperty( key ); assertEquals( array1.length, propertyValue.length ); for ( int i = 0; i < array1.length; i++ ) { assertEquals( array1[i], propertyValue[i] ); } node1.setProperty( key, array2 ); newTransaction(); clearCache(); propertyValue = (char[]) node1.getProperty( key ); assertEquals( array2.length, propertyValue.length ); for ( int i = 0; i < array2.length; i++ ) { assertEquals( array2[i], new Character( propertyValue[i] ) ); } node1.removeProperty( key ); newTransaction(); clearCache(); assertTrue( !node1.hasProperty( key ) ); } @Test public void testEmptyString() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "1", 2 ); node.setProperty( "2", "" ); node.setProperty( "3", "" ); newTransaction(); clearCache(); assertEquals( 2, node.getProperty( "1" ) ); assertEquals( "", node.getProperty( "2" ) ); assertEquals( "", node.getProperty( "3" ) ); } @Test public void shouldNotBeAbleToPoisonBooleanArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new boolean[] {false, false, false}, true ); } @Test public void shouldNotBeAbleToPoisonByteArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new byte[] {0, 0, 0}, (byte)1 ); } @Test public void shouldNotBeAbleToPoisonShortArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new short[] {0, 0, 0}, (short)1 ); } @Test public void shouldNotBeAbleToPoisonIntArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new int[] {0, 0, 0}, 1 ); } @Test public void shouldNotBeAbleToPoisonLongArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new long[] {0, 0, 0}, 1L ); } @Test public void shouldNotBeAbleToPoisonFloatArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new float[] {0F, 0F, 0F}, 1F ); } @Test public void shouldNotBeAbleToPoisonDoubleArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new double[] {0D, 0D, 0D}, 1D ); } @Test public void shouldNotBeAbleToPoisonCharArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new char[] {'0', '0', '0'}, '1' ); } @Test public void shouldNotBeAbleToPoisonStringArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( new String[] {"zero", "zero", "zero"}, "one" ); } private Object veryLongArray( Class<?> type ) { Object array = Array.newInstance( type, 1000 ); return array; } private String[] veryLongStringArray() { String[] array = new String[100]; Arrays.fill( array, "zero" ); return array; } @Test public void shouldNotBeAbleToPoisonVeryLongBooleanArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Boolean.TYPE ), true ); } @Test public void shouldNotBeAbleToPoisonVeryLongByteArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Byte.TYPE ), (byte)1 ); } @Test public void shouldNotBeAbleToPoisonVeryLongShortArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Short.TYPE ), (short)1 ); } @Test public void shouldNotBeAbleToPoisonVeryLongIntArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Integer.TYPE ), 1 ); } @Test public void shouldNotBeAbleToPoisonVeryLongLongArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Long.TYPE ), 1L ); } @Test public void shouldNotBeAbleToPoisonVeryLongFloatArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Float.TYPE ), 1F ); } @Test public void shouldNotBeAbleToPoisonVeryLongDoubleArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Double.TYPE ), 1D ); } @Test public void shouldNotBeAbleToPoisonVeryLongCharArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongArray( Character.TYPE ), '1' ); } @Test public void shouldNotBeAbleToPoisonVeryLongStringArrayProperty() throws Exception { shouldNotBeAbleToPoisonArrayProperty( veryLongStringArray(), "one" ); } private void shouldNotBeAbleToPoisonArrayProperty( Object value, Object poison ) { shouldNotBeAbleToPoisonArrayPropertyInsideTransaction( value, poison ); shouldNotBeAbleToPoisonArrayPropertyOutsideTransaction( value, poison ); } private void shouldNotBeAbleToPoisonArrayPropertyInsideTransaction( Object value, Object poison ) { // GIVEN String key = "key"; // setting a property, then reading it back node1.setProperty( key, value ); Object readValue = node1.getProperty( key ); // WHEN changing the value read back Array.set( readValue, 0, poison ); // THEN reading the value one more time should still yield the set property assertTrue( format( "Expected %s, but was %s", ArrayUtil.toString( value ), ArrayUtil.toString( readValue ) ), ArrayUtil.equals( value, node1.getProperty( key ) ) ); } private void shouldNotBeAbleToPoisonArrayPropertyOutsideTransaction( Object value, Object poison ) { // GIVEN String key = "key"; // setting a property, then reading it back node1.setProperty( key, value ); newTransaction(); clearCache(); Object readValue = node1.getProperty( key ); // WHEN changing the value read back Array.set( readValue, 0, poison ); // THEN reading the value one more time should still yield the set property assertTrue( format( "Expected %s, but was %s", ArrayUtil.toString( value ), ArrayUtil.toString( readValue ) ), ArrayUtil.equals( value, node1.getProperty( key ) ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyTypes.java
892
{ @Override public void run() { Transaction tx = graphdb.beginTx(); try { perform(); tx.success(); } finally { tx.finish(); } } }.start();
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
893
private abstract class TxThread { public TxThread() { new Thread() { @Override public void run() { Transaction tx = graphdb.beginTx(); try { perform(); tx.success(); } finally { tx.finish(); } } }.start(); } abstract void perform(); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
894
private abstract class TX<T> { private final T value; TX() { Transaction tx = graphdb.beginTx(); try { value = perform(); tx.success(); } finally { tx.finish(); } } abstract T perform(); final T result() { return value; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
895
{ @Override Void perform() { first.removeProperty( "key" ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
896
{ @Override Node perform() { Node node = graphdb.createNode(); node.setProperty( "key", "other" ); return node; } }.result();
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
897
{ @Override void perform() { removeProperty( first, "key" ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
898
{ @Override Node perform() { Node node = graphdb.createNode(); node.setProperty( "key", "value" ); return node; } }.result();
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java
899
@ForeignBreakpoints( { @ForeignBreakpoints.BreakpointDef( type = "org.neo4j.kernel.impl.core.ArrayBasedPrimitive", method = "setProperties" ), @ForeignBreakpoints.BreakpointDef( type = "org.neo4j.kernel.impl.core.ArrayBasedPrimitive", method = "commitPropertyMaps", on = BreakPoint.Event.EXIT ) } ) @RunWith( SubProcessTestRunner.class ) @SuppressWarnings( "javadoc" ) @Ignore( "Ignored in 2.0 due to half-way refactoring moving properties into kernel API. " + "Unignore and change appropriately when it's done" ) public class TestPropertyCachePoisoning { @Test @EnabledBreakpoints( { "setProperties", "removeProperty" } ) public void raceBetweenPropertyReaderAndPropertyWriter() { final Node first = new TX<Node>() { @Override Node perform() { Node node = graphdb.createNode(); node.setProperty( "key", "value" ); return node; } }.result(); clearCache(); new TxThread() { @Override void perform() { removeProperty( first, "key" ); } }; first.getProperty( "key", null ); final Node second = new TX<Node>() { @Override Node perform() { Node node = graphdb.createNode(); node.setProperty( "key", "other" ); return node; } }.result(); new TX<Void>() { @Override Void perform() { first.removeProperty( "key" ); return null; } }; clearCache(); assertEquals( "other", second.getProperty( "key" ) ); } private static DebuggedThread readerThread, removerThread; @BeforeDebuggedTest public static void resetThreadReferences() { readerThread = removerThread = null; } @BreakpointTrigger void removeProperty( Node node, String key ) { node.removeProperty( key ); } @BreakpointHandler( "removeProperty" ) public static void handleRemoveProperty( @BreakpointHandler( "commitPropertyMaps" ) BreakPoint exitCommit, DebugInterface di ) { if ( readerThread == null ) { removerThread = di.thread().suspend( null ); } exitCommit.enable(); } @BreakpointHandler( "setProperties" ) public static void handleSetProperties( BreakPoint self, DebugInterface di ) { self.disable(); if ( removerThread != null ) { removerThread.resume(); removerThread = null; } readerThread = di.thread().suspend( DebuggerDeadlockCallback.RESUME_THREAD ); } @BreakpointHandler( value = "commitPropertyMaps" ) public static void exitCommitPropertyMaps( BreakPoint self, DebugInterface di ) { self.disable(); readerThread.resume(); readerThread = null; } private void clearCache() { graphdb.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); } private abstract class TxThread { public TxThread() { new Thread() { @Override public void run() { Transaction tx = graphdb.beginTx(); try { perform(); tx.success(); } finally { tx.finish(); } } }.start(); } abstract void perform(); } private abstract class TX<T> { private final T value; TX() { Transaction tx = graphdb.beginTx(); try { value = perform(); tx.success(); } finally { tx.finish(); } } abstract T perform(); final T result() { return value; } } private GraphDatabaseAPI graphdb; @Before public void startGraphdb() { graphdb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase(); } @After public void stopGraphdb() { try { if ( graphdb != null ) graphdb.shutdown(); } finally { graphdb = null; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestPropertyCachePoisoning.java