public void Survive_Many_Cycles()
        {
            var cycles = 2;
            var item   = new Person("Cervantes");
            var soft   = new SoftReference(item)
            {
                GCCycles = cycles
            };

            ConsoleEx.WriteLine("Survive for the given number of cycles...");
            for (int i = 0; i < cycles; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                ConsoleEx.WriteLine("- Iteration: {0} ==> {1}", i, soft);
                Assert.IsTrue(soft.IsAlive);
            }

            var max = 10; ConsoleEx.WriteLine("\n> Testing for max {0} iterations...", max);

            for (int i = 0; i < max; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                ConsoleEx.WriteLine("- Iteration: {0} ==> {1}", i, soft);
                if (!soft.IsAlive)
                {
                    break;
                }
            }
            Assert.IsFalse(soft.IsAlive);
            Assert.IsTrue(soft.GCCurrentPulses == (cycles * 2));
        }
Exemple #2
0
        public ExpressionResultCacheEntryLongArrayAndObj GetEnumerationMethodLastValue(object node)
        {
            SoftReference<ExpressionResultCacheEntryLongArrayAndObj> cacheRef = enumMethodCache.Get(node);
            if (cacheRef == null) {
                return null;
            }

            ExpressionResultCacheEntryLongArrayAndObj entry = cacheRef.Get();
            if (entry == null) {
                return null;
            }

            long[] required = entry.Reference;
            if (required.Length != lastValueCacheStack.Count) {
                return null;
            }

            IEnumerator<long> prov = lastValueCacheStack.GetEnumerator();
            for (int i = 0; i < lastValueCacheStack.Count; i++) {
                prov.MoveNext();
                if (!Equals(required[i], prov.Current)) {
                    return null;
                }
            }

            return entry;
        }
        public UnserializeCacheEntry(Env env, Value value)
        {
            CopyRoot root = new CopyRoot(this);

            value = value.copyTree(env, root);

            _valueRef = new SoftReference <Value>(value);
        }
        public void Performance()
        {
            Func <string, Action, double> executor = (message, action) =>
            {
                ConsoleEx.WriteLine("\n> {0}", message);

                Stopwatch watch = new Stopwatch();
                watch.Start();
                action();
                watch.Stop();

                var secs = (double)watch.ElapsedMilliseconds / 1000;
                ConsoleEx.WriteLine("- Elapsed: {0} secs.", secs.ToString("#,###.0000"));
                return(secs);
            };

            long   count = 4 * 1000;
            string str   = null;

            str = string.Format("Testing {0} Weak References...", count.ToString("#,###"));
            var std = executor(str, () =>
            {
                for (long i = 0; i < count; i++)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    var obj = new Person(i.ToString());
                    var tmp = new WeakReference(obj);
                    obj     = null;
                }
            });

            str = string.Format("Testing {0} Soft References...", count.ToString("#,###"));
            var neo = executor(str, () =>
            {
                for (long i = 0; i < count; i++)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    var obj = new Person(i.ToString());
                    var tmp = new SoftReference(obj);
                    obj     = null;
                }
            });

            var dif = neo - std;
            var fct = neo / std; if (fct < 1)

            {
                fct = 1 / fct;
            }

            ConsoleEx.WriteLine("\n> Test - Standard = {0} => Factor: {1}",
                                dif.ToString("#,###.0000"),
                                fct.ToString("#,###.00"));
        }
		static DeltaBaseCache()
		{
			DEAD = new SoftReference<DeltaBaseCache.Entry>(null);
			maxByteCount = new WindowCacheConfig().GetDeltaBaseCacheLimit();
			cache = new DeltaBaseCache.Slot[CACHE_SZ];
			for (int i = 0; i < CACHE_SZ; i++)
			{
				cache[i] = new DeltaBaseCache.Slot();
			}
		}
Exemple #6
0
 static DeltaBaseCache()
 {
     DEAD         = new SoftReference <DeltaBaseCache.Entry>(null);
     maxByteCount = new WindowCacheConfig().GetDeltaBaseCacheLimit();
     cache        = new DeltaBaseCache.Slot[CACHE_SZ];
     for (int i = 0; i < CACHE_SZ; i++)
     {
         cache[i] = new DeltaBaseCache.Slot();
     }
 }
Exemple #7
0
        private static T deref <T>(ThreadLocal <SoftReference <T> > tl)
        {
            SoftReference <T> sr = tl.Get();

            if (sr == null)
            {
                return(null);
            }
            return(sr.get());
        }
        private void RegisterRepository(RepositoryCache.Key location, Repository db)
        {
            db.IncrementOpen();
            SoftReference <Repository> newRef = new SoftReference <Repository>(db);
            Reference <Repository>     oldRef = cacheMap.Put(location, newRef);
            Repository oldDb = oldRef != null?oldRef.Get() : null;

            if (oldDb != null)
            {
                oldDb.Close();
            }
        }
            internal ParsingData FetchParsingData()
            {
                ParsingData result = parsingDataCache.Get();

                if (result == null)
                {
                    result = new ParsingData();
                    CurrencySink sink = new CurrencySink(!fallback, CurrencySink.EntrypointTable.TOP);
                    sink.parsingData = result;
                    rb.GetAllItemsWithFallback("", sink);
                    parsingDataCache = new SoftReference <ParsingData>(result);
                }
                return(result);
            }
Exemple #10
0
 internal void Set(Method method)
 {
     if (method == null)
     {
         this.Signature = null;
         this.MethodRef = null;
         this.TypeRef   = null;
     }
     else
     {
         this.Signature = method.toGenericString();
         this.MethodRef = new SoftReference <>(method);
         this.TypeRef   = new WeakReference <Class>(method.DeclaringClass);
     }
 }
        public Value getValue(Env env)
        {
            SoftReference <CopyRoot> copyRef = null;

            if (_freeList != null)
            {
                copyRef = _freeList.allocate();
            }

            if (copyRef != null)
            {
                CopyRoot copy = copyRef.get();

                if (copy != null)
                {
                    copy.allocate(env);

                    return(copy.getRoot());
                }
            }

            Value value = null;

            if (_valueRef != null)
            {
                value = _valueRef.get();
            }

            if (value != null)
            {
                CopyRoot root = new CopyRoot(this);

                root.allocate(env);

                Value copy = value.copyTree(env, root);

                root.setRoot(copy);

                return(copy);
            }
            else
            {
                return(null);
            }
        }
Exemple #12
0
 /// <summary>
 /// Get the value of this
 /// <see cref="Lazy{E}"/>
 /// , computing it if necessary.
 /// </summary>
 public virtual E Get()
 {
     lock (this)
     {
         E orNull = GetIfDefined();
         if (orNull == null)
         {
             orNull = Compute();
             if (IsCache())
             {
                 implOrNullCache = new SoftReference <E>(orNull);
             }
             else
             {
                 implOrNull = orNull;
             }
         }
         System.Diagnostics.Debug.Assert(orNull != null);
         return(orNull);
     }
 }
        public void Survive_While_Used()
        {
            var item = new Person("Cervantes");
            var soft = new SoftReference(item);

            var max = 10; ConsoleEx.WriteLine("\n> Testing for max {0} iterations...", max);

            item = null;
            for (int i = 0; i < max; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                ConsoleEx.WriteLine("- Iteration: {0} ==> {1}", i, soft);

                var target = soft.Target;
                Assert.IsNotNull(target);
                Assert.IsTrue(soft.IsAlive);
            }
            Assert.IsNotNull(soft.WeakTarget);
            Assert.IsNotNull(soft.RawTarget);
            Assert.IsTrue(soft.IsAlive);
        }
Exemple #14
0
            /// <summary>
            /// creates a
            /// <see cref="Sharpen.SimpleDateFormat">Sharpen.SimpleDateFormat</see>
            /// for the requested format string.
            /// </summary>
            /// <param name="pattern">
            /// a non-<code>null</code> format String according to
            /// <see cref="Sharpen.SimpleDateFormat">Sharpen.SimpleDateFormat</see>
            /// . The format is not checked against
            /// <code>null</code> since all paths go through
            /// <see cref="DateUtils">DateUtils</see>
            /// .
            /// </param>
            /// <returns>
            /// the requested format. This simple dateformat should not be used
            /// to
            /// <see cref="Sharpen.SimpleDateFormat.ApplyPattern(string)">apply</see>
            /// to a
            /// different pattern.
            /// </returns>
            public static SimpleDateFormat FormatFor(string pattern)
            {
                SoftReference <IDictionary <string, SimpleDateFormat> > @ref = ThreadlocalFormats.Get
                                                                                   ();
                IDictionary <string, SimpleDateFormat> formats = @ref.Get();

                if (formats == null)
                {
                    formats = new Dictionary <string, SimpleDateFormat>();
                    ThreadlocalFormats.Set(new SoftReference <IDictionary <string, SimpleDateFormat> >(formats
                                                                                                       ));
                }
                SimpleDateFormat format = formats.Get(pattern);

                if (format == null)
                {
                    format = new SimpleDateFormat(pattern, CultureInfo.InvariantCulture);
                    format.SetTimeZone(Sharpen.Extensions.GetTimeZone("GMT"));
                    formats.Put(pattern, format);
                }
                return(format);
            }
Exemple #15
0
 /// <summary>
 /// Try to add a value to the map.
 /// </summary>
 internal T Add(string key, T value)
 {
     while (true)
     {
         var newEntry = new SoftReference <T>(value);
         var entry    = map.PutIfAbsent(key, newEntry);
         if (entry != null)
         {
             // There was an entry in the map.
             var result = entry.Get();
             if (result != null)
             {
                 // The entry holds a valid reference, we're done
                 return(result);
             }
             else
             {
                 // The entry has been cleared
                 map.Replace(key, newEntry);
             }
         }
     }
 }
Exemple #16
0
        /// <exception cref="System.IO.IOException"></exception>
        private Repository OpenRepository(RepositoryCache.Key location, bool mustExist)
        {
            Reference <Repository> @ref = cacheMap.Get(location);
            Repository             db   = @ref != null? @ref.Get() : null;

            if (db == null)
            {
                lock (LockFor(location))
                {
                    @ref = cacheMap.Get(location);
                    db   = @ref != null? @ref.Get() : null;

                    if (db == null)
                    {
                        db   = location.Open(mustExist);
                        @ref = new SoftReference <Repository>(db);
                        cacheMap.Put(location, @ref);
                    }
                }
            }
            db.IncrementOpen();
            return(db);
        }
Exemple #17
0
        /// <summary>
        /// Gets the Collator for the desired locale. </summary>
        /// <param name="desiredLocale"> the desired locale. </param>
        /// <returns> the Collator for the desired locale. </returns>
        /// <seealso cref= java.util.Locale </seealso>
        /// <seealso cref= java.util.ResourceBundle </seealso>
        public static Collator GetInstance(Locale desiredLocale)
        {
            SoftReference <Collator> @ref = Cache[desiredLocale];
            Collator result = (@ref != null) ? @ref.get() : null;

            if (result == null)
            {
                LocaleProviderAdapter adapter;
                adapter = LocaleProviderAdapter.getAdapter(typeof(CollatorProvider), desiredLocale);
                CollatorProvider provider = adapter.CollatorProvider;
                result = provider.GetInstance(desiredLocale);
                if (result == null)
                {
                    result = LocaleProviderAdapter.forJRE().CollatorProvider.getInstance(desiredLocale);
                }
                while (true)
                {
                    if (@ref != null)
                    {
                        // Remove the empty SoftReference if any
                        Cache.Remove(desiredLocale, @ref);
                    }
                    @ref = Cache.PutIfAbsent(desiredLocale, new SoftReference <>(result));
                    if (@ref == null)
                    {
                        break;
                    }
                    Collator cachedColl = @ref.get();
                    if (cachedColl != null)
                    {
                        result = cachedColl;
                        break;
                    }
                }
            }
            return((Collator)result.Clone());             // make the world safe
        }
Exemple #18
0
        internal Method Get()
        {
            if (this.MethodRef == null)
            {
                return(null);
            }
            Method method = this.MethodRef.get();

            if (method == null)
            {
                method = Find(this.TypeRef.get(), this.Signature);
                if (method == null)
                {
                    this.Signature = null;
                    this.MethodRef = null;
                    this.TypeRef   = null;
                }
                else
                {
                    this.MethodRef = new SoftReference <>(method);
                }
            }
            return(isPackageAccessible(method.DeclaringClass) ? method : null);
        }
Exemple #19
0
        /**
         * It's like {@link FloatBuffer#put(float[])}, but about 10 times faster
         */
        public void Put(float[] data)
        {
            int length = data.Length;

            int[] ia = sWeakIntArray.Get();
            if (ia == null || ia.Length < length)
            {
                ia            = new int[length];
                sWeakIntArray = new SoftReference <int[]>(ia);
            }

            for (int i = 0; i < length; i++)
            {
                ia[i] = Float.FloatToRawIntBits(data[i]);
            }

            ByteBuffer byteBuffer = this.mByteBuffer;

            byteBuffer.Position(byteBuffer.Position() + GLHelper.BYTES_PER_FLOAT * length);
            FloatBuffer floatBuffer = this.mFloatBuffer;

            floatBuffer.Position(floatBuffer.Position() + length);
            this.mIntBuffer.Put(ia, 0, length);
        }
        public void Expires_After_Next_GC()
        {
            var item = new Person("Cervantes");
            var soft = new SoftReference(item);

            Assert.IsTrue(soft.IsAlive);
            Assert.IsNotNull(soft.WeakTarget);
            Assert.IsNotNull(soft.RawTarget);

            ConsoleEx.WriteLine("\n> First collection...");
            item = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.IsTrue(soft.IsAlive);
            Assert.IsNotNull(soft.WeakTarget);
            Assert.IsTrue(soft.RawTarget == null);

            ConsoleEx.WriteLine("\n> Second collection...");
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.IsFalse(soft.IsAlive);
            Assert.IsTrue(soft.WeakTarget == null);
            Assert.IsTrue(soft.RawTarget == null);
        }
 public UnserializeCacheEntry(Value value)
 {
     _valueRef = new SoftReference <Value>(value);
 }
 static DeltaBaseCache()
 {
     DEAD = new SoftReference <DeltaBaseCache.Entry>(null);
     Reconfigure(new WindowCacheConfig());
 }
        private void InitializeData(Locale desiredLocale)
        {
            Locale = desiredLocale;

            // Copy values of a cached instance if any.
            SoftReference <DateFormatSymbols> @ref = CachedInstances[Locale];
            DateFormatSymbols dfs;

            if (@ref != null && (dfs = @ref.get()) != null)
            {
                CopyMembers(dfs, this);
                return;
            }

            // Initialize the fields from the ResourceBundle for locale.
            LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(typeof(DateFormatSymbolsProvider), Locale);

            // Avoid any potential recursions
            if (!(adapter is ResourceBundleBasedAdapter))
            {
                adapter = LocaleProviderAdapter.ResourceBundleBased;
            }
            ResourceBundle resource = ((ResourceBundleBasedAdapter)adapter).LocaleData.getDateFormatData(Locale);

            // JRE and CLDR use different keys
            // JRE: Eras, short.Eras and narrow.Eras
            // CLDR: long.Eras, Eras and narrow.Eras
            if (resource.ContainsKey("Eras"))
            {
                Eras_Renamed = resource.GetStringArray("Eras");
            }
            else if (resource.ContainsKey("long.Eras"))
            {
                Eras_Renamed = resource.GetStringArray("long.Eras");
            }
            else if (resource.ContainsKey("short.Eras"))
            {
                Eras_Renamed = resource.GetStringArray("short.Eras");
            }
            Months_Renamed      = resource.GetStringArray("MonthNames");
            ShortMonths_Renamed = resource.GetStringArray("MonthAbbreviations");
            Ampms = resource.GetStringArray("AmPmMarkers");
            LocalPatternChars_Renamed = resource.GetString("DateTimePatternChars");

            // Day of week names are stored in a 1-based array.
            Weekdays_Renamed      = ToOneBasedArray(resource.GetStringArray("DayNames"));
            ShortWeekdays_Renamed = ToOneBasedArray(resource.GetStringArray("DayAbbreviations"));

            // Put a clone in the cache
            @ref = new SoftReference <>((DateFormatSymbols)this.Clone());
            SoftReference <DateFormatSymbols> x = CachedInstances.PutIfAbsent(Locale, @ref);

            if (x != null)
            {
                DateFormatSymbols y = x.get();
                if (y == null)
                {
                    // Replace the empty SoftReference with ref.
                    CachedInstances[Locale] = @ref;
                }
            }
        }
Exemple #24
0
        public QuercusPage parseImpl(Path path, string fileName, int line)

        {
            try {
                SoftReference <QuercusProgram> programRef = _programCache.get(path);

                QuercusProgram program = programRef != null?programRef.get() : null;

                bool isModified = false;

                if (program != null)
                {
                    isModified = program.isModified();

                    if (program.isCompilable())
                    {
                    }
                    else if (isModified)
                    {
                        program.setCompilable(true);
                    }
                    else
                    {
                        if (log.isLoggable(Level.FINE))
                        {
                            log.fine(L.l("Quercus[{0}] loading interpreted page", path));
                        }

                        return(new InterpretedPage(program));
                    }
                }

                if (program == null || isModified)
                {
                    clearProgram(path, program);

                    program = preloadProgram(path, fileName);

                    if (program == null)
                    {
                        if (log.isLoggable(Level.FINE))
                        {
                            log.fine(L.l("Quercus[{0}] parsing page", path));
                        }

                        program = QuercusParser.parse(_quercus,
                                                      path,
                                                      _quercus.getScriptEncoding(),
                                                      fileName,
                                                      line);
                    }

                    _programCache.put(path, new SoftReference <QuercusProgram>(program));
                }

                if (program.getCompiledPage() != null)
                {
                    return(program.getCompiledPage());
                }

                return(compilePage(program, path));
            } catch (IOException e) {
                throw e;
            } catch (RuntimeException e) {
                throw e;
            } catch (Throwable e) {
                throw new IOExceptionWrapper(e);
            }
        }
Exemple #25
0
		private void RegisterRepository(RepositoryCache.Key location, Repository db)
		{
			db.IncrementOpen();
			SoftReference<Repository> newRef = new SoftReference<Repository>(db);
			Reference<Repository> oldRef = cacheMap.Put(location, newRef);
			Repository oldDb = oldRef != null ? oldRef.Get() : null;
			if (oldDb != null)
			{
				oldDb.Close();
			}
		}
Exemple #26
0
		/// <exception cref="System.IO.IOException"></exception>
		private Repository OpenRepository(RepositoryCache.Key location, bool mustExist)
		{
			Reference<Repository> @ref = cacheMap.Get(location);
			Repository db = @ref != null ? @ref.Get() : null;
			if (db == null)
			{
				lock (LockFor(location))
				{
					@ref = cacheMap.Get(location);
					db = @ref != null ? @ref.Get() : null;
					if (db == null)
					{
						db = location.Open(mustExist);
						@ref = new SoftReference<Repository>(db);
						cacheMap.Put(location, @ref);
					}
				}
			}
			db.IncrementOpen();
			return db;
		}
Exemple #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="target">The target object</param>
 /// <param name="trackResurrection">not used by Dot42</param>
 public WeakReference(object target, bool trackResurrection)
 {
     softReference          = new SoftReference <object>(target);
     this.trackResurrection = trackResurrection;
 }
        private static sbyte[] InitNamePool()
        {
            lock (typeof(CharacterName))
            {
                sbyte[] strPool = null;
                if (RefStrPool != null && (strPool = RefStrPool.get()) != null)
                {
                    return(strPool);
                }
                DataInputStream dis = null;
                try
                {
                    dis = new DataInputStream(new InflaterInputStream(AccessController.doPrivileged(new PrivilegedActionAnonymousInnerClassHelper())));

                    Lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][];
                    int     total = dis.ReadInt();
                    int     cpEnd = dis.ReadInt();
                    sbyte[] ba    = new sbyte[cpEnd];
                    dis.ReadFully(ba);

                    int nameOff = 0;
                    int cpOff   = 0;
                    int cp      = 0;
                    do
                    {
                        int len = ba[cpOff++] & 0xff;
                        if (len == 0)
                        {
                            len = ba[cpOff++] & 0xff;
                            // always big-endian
                            cp = ((ba[cpOff++] & 0xff) << 16) | ((ba[cpOff++] & 0xff) << 8) | ((ba[cpOff++] & 0xff));
                        }
                        else
                        {
                            cp++;
                        }
                        int hi = cp >> 8;
                        if (Lookup[hi] == null)
                        {
                            Lookup[hi] = new int[0x100];
                        }
                        Lookup[hi][cp & 0xff] = (nameOff << 8) | len;
                        nameOff += len;
                    } while (cpOff < cpEnd);
                    strPool = new sbyte[total - cpEnd];
                    dis.ReadFully(strPool);
                    RefStrPool = new SoftReference <>(strPool);
                }
                catch (Exception x)
                {
                    throw new InternalError(x.Message, x);
                }
                finally
                {
                    try
                    {
                        if (dis != null)
                        {
                            dis.Close();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                return(strPool);
            }
        }
Exemple #29
0
		static DeltaBaseCache()
		{
			DEAD = new SoftReference<DeltaBaseCache.Entry>(null);
			Reconfigure(new WindowCacheConfig());
		}
Exemple #30
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="target">The target object</param>
 /// <param name="trackResurrection">not used by Dot42</param>
 public WeakReference(object target, bool trackResurrection)
 {
     softReference = new SoftReference<object>(target);
     this.trackResurrection = trackResurrection;
 }
 public void clear()
 {
     _valueRef = null;
     _freeList = null;
 }