Exemplo n.º 1
0
        public virtual V get(K key)
        {
            V value = cache.get(key);

            if (value != default(V))
            {
                keys.remove(key);
                keys.add(key);
            }
            return(value);
        }
Exemplo n.º 2
0
        /// <summary>
        /// End the life of a stored entry. If the entry is currently in use, it will be thrown out as soon as the other client
        /// is done with it.
        /// </summary>
        public virtual VALUE End(KEY key)
        {
            while (true)
            {
                Entry entry = _repo.get(key);
                if (entry == null)
                {
                    return(default(VALUE));
                }

                // Ending the life of an entry is somewhat complicated, because we promise the callee here that if someone
                // else is concurrently using the entry, we will ensure that either we or the other user will end the entry
                // life when the other user is done with it.

                // First, assume the entry is in use and try and mark it to be ended by the other user
                if (entry.MarkForEndingIfInUse())
                {
                    // The entry was indeed in use, and we successfully marked it to be ended. That's all we need to do here,
                    // the other user will see the ending flag when releasing the entry.
                    return(entry.Value);
                }

                // Marking it for ending failed, likely because the entry is currently idle - lets try and just acquire it
                // and throw it out ourselves
                if (entry.Acquire())
                {
                    // Got it, just throw it away
                    End0(key, entry.Value);
                    return(entry.Value);
                }

                // We didn't manage to mark this for ending, and we didn't manage to acquire it to end it ourselves, which
                // means either we're racing with another thread using it (and we just need to retry), or it's already
                // marked for ending. In the latter case, we can bail here.
                if (entry.MarkedForEnding)
                {
                    // Someone did indeed manage to mark it for ending, which means it will be thrown out (or has already).
                    return(entry.Value);
                }
            }
        }
Exemplo n.º 3
0
        public override void ReleaseExclusive(ResourceType resourceType, params long[] resourceIds)
        {
            _stateHolder.incrementActiveClients(this);

            try
            {
                ConcurrentMap <long, ForsetiLockManager.Lock> resourceTypeLocks = _lockMaps[resourceType.TypeId()];
                MutableLongIntMap exclusiveLocks = _exclusiveLockCounts[resourceType.TypeId()];
                MutableLongIntMap sharedLocks    = _sharedLockCounts[resourceType.TypeId()];
                foreach (long resourceId in resourceIds)
                {
                    if (ReleaseLocalLock(resourceType, resourceId, exclusiveLocks))
                    {
                        continue;
                    }

                    if (sharedLocks.containsKey(resourceId))
                    {
                        // We are still holding a shared lock, so we will release it to be reused
                        ForsetiLockManager.Lock @lock = resourceTypeLocks.get(resourceId);
                        if (@lock is SharedLock)
                        {
                            SharedLock sharedLock = ( SharedLock )@lock;
                            if (sharedLock.UpdateLock)
                            {
                                sharedLock.ReleaseUpdateLock();
                            }
                            else
                            {
                                throw new System.InvalidOperationException("Incorrect state of exclusive lock. Lock should be updated " + "to exclusive before attempt to release it. Lock: " + this);
                            }
                        }
                        else
                        {
                            // in case if current lock is exclusive we swap it to new shared lock
                            SharedLock sharedLock = new SharedLock(this);
                            resourceTypeLocks.put(resourceId, sharedLock);
                        }
                    }
                    else
                    {
                        // we do not hold shared lock so we just releasing it
                        ReleaseGlobalLock(resourceTypeLocks, resourceId);
                    }
                }
            }
            finally
            {
                _stateHolder.decrementActiveClients();
            }
        }
Exemplo n.º 4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static <Key> boolean performLookup(ReadableState<Key> store, org.neo4j.io.pagecache.tracing.cursor.context.VersionContext versionContext, java.util.concurrent.ConcurrentMap<Key,ChangeEntry> changes, Key key, ValueSink sink) throws java.io.IOException
        private static bool PerformLookup <Key>(ReadableState <Key> store, VersionContext versionContext, ConcurrentMap <Key, ChangeEntry> changes, Key key, ValueSink sink)
        {
            ChangeEntry change = changes.get(key);

            if (change != null)
            {
                if (change.Version > versionContext.LastClosedTransactionId())
                {
                    versionContext.MarkAsDirty();
                }
                sink.Value(new BigEndianByteArrayBuffer(change.Data));
                return(true);
            }
            return(store.Lookup(key, sink));
        }
Exemplo n.º 5
0
        public override object build <T1>(Type beanType, BeanBuilder <T1> builder)
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: org.joda.beans.impl.BufferingBeanBuilder<?> bld = (org.joda.beans.impl.BufferingBeanBuilder<?>) builder;
            BufferingBeanBuilder <object> bld = (BufferingBeanBuilder <object>)builder;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.ConcurrentMap<org.joda.beans.MetaProperty<?>, Object> buffer = bld.getBuffer();
            ConcurrentMap <MetaProperty <object>, object> buffer = bld.Buffer;
            BusinessDayAdjustment bda = (BusinessDayAdjustment)buffer.getOrDefault(PAYMENT_ADJUSTMENT_DATE, null);

            if (buffer.containsKey(BASE_CURRENCY_AMOUNT) && buffer.containsKey(COUNTER_CURRENCY_AMOUNT) && buffer.containsKey(PAYMENT_DATE))
            {
                CurrencyAmount baseAmount    = (CurrencyAmount)builder.get(BASE_CURRENCY_AMOUNT);
                CurrencyAmount counterAmount = (CurrencyAmount)builder.get(COUNTER_CURRENCY_AMOUNT);
                LocalDate      paymentDate   = (LocalDate)builder.get(PAYMENT_DATE);
                return(bda != null?FxSingle.of(baseAmount, counterAmount, paymentDate, bda) : FxSingle.of(baseAmount, counterAmount, paymentDate));
            }
            else
            {
                Payment basePayment    = (Payment)buffer.get(BASE_CURRENCY_PAYMENT);
                Payment counterPayment = (Payment)buffer.get(COUNTER_CURRENCY_PAYMENT);
                return(bda != null?FxSingle.of(basePayment, counterPayment, bda) : FxSingle.of(basePayment, counterPayment));
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Release a lock from the global pool. </summary>
 private void ReleaseGlobalLock(ConcurrentMap <long, ForsetiLockManager.Lock> lockMap, long resourceId)
 {
     ForsetiLockManager.Lock @lock = lockMap.get(resourceId);
     if (@lock is ExclusiveLock)
     {
         lockMap.remove(resourceId);
     }
     else if (@lock is SharedLock && (( SharedLock )@lock).Release(this))
     {
         // We were the last to hold this lock, it is now dead and we should remove it.
         // Also cleaning updater reference that can hold lock in memory
         (( SharedLock )@lock).CleanUpdateHolder();
         lockMap.remove(resourceId);
     }
 }
Exemplo n.º 7
0
        //-------------------------------------------------------------------------
        public override FraConvention lookup(string name)
        {
            FraConvention value = BY_NAME.get(name);

            if (value == null)
            {
                FraConvention created = createByName(name);
                if (created != null)
                {
                    string correctName = created.Name;
                    value = BY_NAME.computeIfAbsent(correctName, k => created);
                    BY_NAME.putIfAbsent(correctName.ToUpper(Locale.ENGLISH), value);
                }
            }
            return(value);
        }
Exemplo n.º 8
0
        private AuthenticationMetadata AuthMetadataFor(string username)
        {
            AuthenticationMetadata authMeta = _authenticationData.get(username);

            if (authMeta == null)
            {
                authMeta = new AuthenticationMetadata(this);
                AuthenticationMetadata preExisting = _authenticationData.putIfAbsent(username, authMeta);
                if (preExisting != null)
                {
                    authMeta = preExisting;
                }
            }

            return(authMeta);
        }
Exemplo n.º 9
0
        internal void CasLeaders(LeaderInfo leaderInfo, string dbName)
        {
            lock ( _leaderMap )
            {
                Optional <LeaderInfo> current = Optional.ofNullable(_leaderMap.get(dbName));

//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                bool sameLeader = current.map(LeaderInfo::memberId).Equals(Optional.ofNullable(leaderInfo.MemberId()));

                int termComparison = current.map(l => Long.compare(l.term(), leaderInfo.Term())).orElse(-1);

                bool greaterTermExists = termComparison > 0;

                bool sameTermButNoStepDown = termComparison == 0 && !leaderInfo.SteppingDown;

                if (!(greaterTermExists || sameTermButNoStepDown || sameLeader))
                {
                    _leaderMap.put(dbName, leaderInfo);
                }
            }
        }
Exemplo n.º 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") static <Key> void applyUpdate(ReadableState<Key> store, java.util.concurrent.ConcurrentMap<Key, ChangeEntry> changes, Key key, ValueUpdate update, boolean reset, long version) throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal static void ApplyUpdate <Key>(ReadableState <Key> store, ConcurrentMap <Key, ChangeEntry> changes, Key key, ValueUpdate update, bool reset, long version)
        {
            ChangeEntry value = changes.get(key);

            if (value == null)
            {
                ChangeEntry newEntry = ChangeEntry.Of(new sbyte[store.KeyFormat().valueSize()], version);
                lock ( newEntry )
                {
                    value = changes.putIfAbsent(key, newEntry);
                    if (value == null)
                    {
                        BigEndianByteArrayBuffer buffer = new BigEndianByteArrayBuffer(newEntry.Data);
                        if (!reset)
                        {
                            PreviousValue lookup = new PreviousValue(newEntry.Data);
                            if (!store.Lookup(key, lookup))
                            {
                                buffer.Clear();
                            }
                        }
                        update.Update(buffer);
                        return;
                    }
                }
            }
            lock ( value )
            {
                BigEndianByteArrayBuffer target = new BigEndianByteArrayBuffer(value.Data);
                value.Version = version;
                if (reset)
                {
                    target.Clear();
                }
                update.Update(target);
            }
        }
Exemplo n.º 11
0
 internal virtual FulltextIndexAccessor GetOpenOnlineAccessor(StoreIndexDescriptor descriptor)
 {
     return(_openOnlineAccessors.get(descriptor));
 }
Exemplo n.º 12
0
 internal CoreTopology GetCoreTopology(string dbName, bool canBeBootstrapped)
 {
     return(new CoreTopology(_clusterIdDbNames.get(dbName), canBeBootstrapped, Collections.unmodifiableMap(_coreMembers)));
 }
Exemplo n.º 13
0
        public override bool TrySharedLock(ResourceType resourceType, long resourceId)
        {
            _hasLocks = true;
            _stateHolder.incrementActiveClients(this);

            try
            {
                ConcurrentMap <long, ForsetiLockManager.Lock> lockMap = _lockMaps[resourceType.TypeId()];
                MutableLongIntMap heldShareLocks     = _sharedLockCounts[resourceType.TypeId()];
                MutableLongIntMap heldExclusiveLocks = _exclusiveLockCounts[resourceType.TypeId()];

                int heldCount = heldShareLocks.getIfAbsent(resourceId, -1);
                if (heldCount != -1)
                {
                    // We already have a lock on this, just increment our local reference counter.
                    heldShareLocks.put(resourceId, Math.incrementExact(heldCount));
                    return(true);
                }

                if (heldExclusiveLocks.containsKey(resourceId))
                {
                    // We already have an exclusive lock, so just leave that in place. When the exclusive lock is released,
                    // it will be automatically downgraded to a shared lock, since we bumped the share lock reference count.
                    heldShareLocks.put(resourceId, 1);
                    return(true);
                }

                long waitStartMillis = _clock.millis();
                while (true)
                {
                    AssertValid(waitStartMillis, resourceType, resourceId);

                    ForsetiLockManager.Lock existingLock = lockMap.get(resourceId);
                    if (existingLock == null)
                    {
                        // Try to create a new shared lock
                        if (lockMap.putIfAbsent(resourceId, new SharedLock(this)) == null)
                        {
                            // Success!
                            break;
                        }
                    }
                    else if (existingLock is SharedLock)
                    {
                        // Note that there is a "safe" race here where someone may be releasing the last reference to a lock
                        // and thus removing that lock instance (making it unacquirable). In this case, we allow retrying,
                        // even though this is a try-lock call.
                        if ((( SharedLock )existingLock).Acquire(this))
                        {
                            // Success!
                            break;
                        }
                        else if ((( SharedLock )existingLock).UpdateLock)
                        {
                            return(false);
                        }
                    }
                    else if (existingLock is ExclusiveLock)
                    {
                        return(false);
                    }
                    else
                    {
                        throw new System.NotSupportedException("Unknown lock type: " + existingLock);
                    }
                }
                heldShareLocks.put(resourceId, 1);
                return(true);
            }
            finally
            {
                _stateHolder.decrementActiveClients();
            }
        }
Exemplo n.º 14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void acquireShared(org.neo4j.storageengine.api.lock.LockTracer tracer, org.neo4j.storageengine.api.lock.ResourceType resourceType, long... resourceIds) throws org.neo4j.storageengine.api.lock.AcquireLockTimeoutException
        public override void AcquireShared(LockTracer tracer, ResourceType resourceType, params long[] resourceIds)
        {
            _hasLocks = true;
            _stateHolder.incrementActiveClients(this);
            LockWaitEvent waitEvent = null;

            try
            {
                // Grab the global lock map we will be using
                ConcurrentMap <long, ForsetiLockManager.Lock> lockMap = _lockMaps[resourceType.TypeId()];

                // And grab our local lock maps
                MutableLongIntMap heldShareLocks     = _sharedLockCounts[resourceType.TypeId()];
                MutableLongIntMap heldExclusiveLocks = _exclusiveLockCounts[resourceType.TypeId()];

                foreach (long resourceId in resourceIds)
                {
                    // First, check if we already hold this as a shared lock
                    int heldCount = heldShareLocks.getIfAbsent(resourceId, -1);
                    if (heldCount != -1)
                    {
                        // We already have a lock on this, just increment our local reference counter.
                        heldShareLocks.put(resourceId, Math.incrementExact(heldCount));
                        continue;
                    }

                    // Second, check if we hold it as an exclusive lock
                    if (heldExclusiveLocks.containsKey(resourceId))
                    {
                        // We already have an exclusive lock, so just leave that in place.
                        // When the exclusive lock is released, it will be automatically downgraded to a shared lock,
                        // since we bumped the share lock reference count.
                        heldShareLocks.put(resourceId, 1);
                        continue;
                    }

                    // We don't hold the lock, so we need to grab it via the global lock map
                    int        tries           = 0;
                    SharedLock mySharedLock    = null;
                    long       waitStartMillis = _clock.millis();

                    // Retry loop
                    while (true)
                    {
                        AssertValid(waitStartMillis, resourceType, resourceId);

                        // Check if there is a lock for this entity in the map
                        ForsetiLockManager.Lock existingLock = lockMap.get(resourceId);

                        // No lock
                        if (existingLock == null)
                        {
                            // Try to create a new shared lock
                            if (mySharedLock == null)
                            {
                                mySharedLock = new SharedLock(this);
                            }

                            if (lockMap.putIfAbsent(resourceId, mySharedLock) == null)
                            {
                                // Success, we now hold the shared lock.
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        // Someone holds shared lock on this entity, try and get in on that action
                        else if (existingLock is SharedLock)
                        {
                            if ((( SharedLock )existingLock).Acquire(this))
                            {
                                // Success!
                                break;
                            }
                        }

                        // Someone holds an exclusive lock on this entity
                        else if (existingLock is ExclusiveLock)
                        {
                            // We need to wait, just let the loop run.
                        }
                        else
                        {
                            throw new System.NotSupportedException("Unknown lock type: " + existingLock);
                        }

                        if (waitEvent == null)
                        {
                            waitEvent = tracer.WaitForLock(false, resourceType, resourceId);
                        }
                        // And take note of who we are waiting for. This is used for deadlock detection.
                        WaitFor(existingLock, resourceType, resourceId, false, tries++);
                    }

                    // Make a local note about the fact that we now hold this lock
                    heldShareLocks.put(resourceId, 1);
                }
            }
            finally
            {
                if (waitEvent != null)
                {
                    waitEvent.Close();
                }
                ClearWaitList();
                _waitingForLock = null;
                _stateHolder.decrementActiveClients();
            }
        }