Java Code Examples for java.lang.ref.SoftReference

The following examples show how to use java.lang.ref.SoftReference. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public synchronized Enumeration getFinalizerObjects() {
    Vector obj;
    if (finalizablesCache != null &&
        (obj = finalizablesCache.get()) != null) {
        return obj.elements();
    }

    JavaClass clazz = findClass("java.lang.ref.Finalizer");
    JavaObject queue = (JavaObject) clazz.getStaticField("queue");
    JavaThing tmp = queue.getField("head");
    Vector<JavaHeapObject> finalizables = new Vector<JavaHeapObject>();
    if (tmp != getNullThing()) {
        JavaObject head = (JavaObject) tmp;
        while (true) {
            JavaHeapObject referent = (JavaHeapObject) head.getField("referent");
            JavaThing next = head.getField("next");
            if (next == getNullThing() || next.equals(head)) {
                break;
            }
            head = (JavaObject) next;
            finalizables.add(referent);
        }
    }
    finalizablesCache = new SoftReference<Vector>(finalizables);
    return finalizables.elements();
}
 
Example 2
Source Project: TencentKona-8   Source File: ZoneInfoOld.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
* Returns a Map from alias time zone IDs to their standard
* time zone IDs.
*
* @return the Map that holds the mappings from alias time zone IDs
*    to their standard time zone IDs, or null if
*    <code>ZoneInfoOldMappings</code> file is not available.
*/
public synchronized static Map<String, String> getAliasTable() {
    Map<String, String> aliases = getCachedAliasTable();
    if (aliases == null) {
        aliases = ZoneInfoFile.getZoneAliases();
        if (aliases != null) {
            if (!USE_OLDMAPPING) {
                // Remove the conflicting IDs from the alias table.
                for (String key : conflictingIDs) {
                    aliases.remove(key);
                }
            }
            aliasTable = new SoftReference<Map<String, String>>(aliases);
        }
    }
    return aliases;
}
 
Example 3
Source Project: netbeans   Source File: AbstractNbTaskWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void taskDataUpdated (TaskDataListener.TaskDataEvent event) {
    if (event.getTask() == task) {
        if (event.getTaskData() != null && !event.getTaskData().isPartial()) {
            repositoryDataRef = new SoftReference<TaskData>(event.getTaskData());
        }
        if (event.getTaskDataUpdated()) {
            NbTaskDataModel m = model;
            if (m != null) {
                try {
                    m.refresh();
                } catch (CoreException ex) {
                    LOG.log(Level.INFO, null, ex);
                }
            }
            AbstractNbTaskWrapper.this.taskDataUpdated();
        }
    }
}
 
Example 4
Source Project: openjdk-jdk9   Source File: StrikeCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Reference<FontStrike> getStrikeRef(FontStrike strike, boolean weak) {
    /* Some strikes may have no disposer as there's nothing
     * for them to free, as they allocated no native resource
     * eg, if they did not allocate resources because of a problem,
     * or they never hold native resources. So they create no disposer.
     * But any strike that reaches here that has a null disposer is
     * a potential memory leak.
     */
    if (strike.disposer == null) {
        if (weak) {
            return new WeakReference<>(strike);
        } else {
            return new SoftReference<>(strike);
        }
    }

    if (weak) {
        return new WeakDisposerRef(strike);
    } else {
        return new SoftDisposerRef(strike);
    }
}
 
Example 5
Source Project: baratine   Source File: LogManagerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the named logger.
 */
@Override
public synchronized Logger getLogger(String name)
{
  SoftReference<EnvironmentLogger> envLoggerRef = _envLoggers.get(name);
  
  EnvironmentLogger envLogger = null;
  if (envLoggerRef != null)
    envLogger = envLoggerRef.get();

  if (envLogger == null)
    envLogger = addLogger(name, null);

  Logger customLogger = envLogger.getLogger();

  if (customLogger != null)
    return customLogger;
  else
    return envLogger;
}
 
Example 6
ManagedChannelReference(
    ManagedChannelOrphanWrapper orphanable,
    ManagedChannel channel,
    ReferenceQueue<ManagedChannelOrphanWrapper> refqueue,
    ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs) {
  super(orphanable, refqueue);
  allocationSite = new SoftReference<RuntimeException>(
      ENABLE_ALLOCATION_TRACKING
          ? new RuntimeException("ManagedChannel allocation site")
          : missingCallSite);
  this.channel = channel;
  this.refqueue = refqueue;
  this.refs = refs;
  this.refs.put(this, this);
  cleanQueue(refqueue);
}
 
Example 7
Source Project: dragonwell8_jdk   Source File: ImageCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Entry getEntry(Object key, GraphicsConfiguration config,
                       int w, int h, Object[] args) {
    Entry entry;
    Iterator<SoftReference<Entry>> iter = entries.listIterator();
    while (iter.hasNext()) {
        SoftReference<Entry> ref = iter.next();
        entry = ref.get();
        if (entry == null) {
            // SoftReference was invalidated, remove the entry
            iter.remove();
        }
        else if (entry.equals(config, w, h, args)) {
            // Put most recently used entries at the head
            iter.remove();
            entries.addFirst(ref);
            return entry;
        }
    }
    // Entry doesn't exist
    entry = new Entry(config, w, h, args);
    if (entries.size() >= maxCount) {
        entries.removeLast();
    }
    entries.addFirst(new SoftReference<Entry>(entry));
    return entry;
}
 
Example 8
Source Project: netbeans   Source File: FolderOrder.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates order for given folder object.
* @param f the folder
* @return the order
*/
public static FolderOrder findFor (FileObject folder) {
    FolderOrder order = null;
    synchronized (map) {
        Reference<FolderOrder> ref = map.get (folder);
        order = ref == null ? null : ref.get ();
        if (order == null) {
            order = new FolderOrder (folder);
            order.previous = knownOrders.get(folder);
            order.doRead(order.previous);
            
            map.put (folder, new SoftReference<FolderOrder> (order));
        }
    }
    // always reread the order from disk, so it is uptodate
    synchronized (order) {
        order.read ();
        return order;            
    }        
}
 
Example 9
Source Project: xtext-extras   Source File: ResolvedFeaturesTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSoftReferenceConstructors() {
  final ResolvedFeatures resolvedOperations = this.toResolvedOperations(SoftReference.class);
  Assert.assertEquals(1, resolvedOperations.getDeclaredOperations().size());
  Assert.assertEquals(2, resolvedOperations.getDeclaredConstructors().size());
  final Consumer<IResolvedConstructor> _function = (IResolvedConstructor it) -> {
    int _size = it.getDeclaration().getParameters().size();
    switch (_size) {
      case 1:
        Assert.assertEquals("SoftReference(T)", it.getResolvedSignature());
        Assert.assertEquals("SoftReference(java.lang.Object)", it.getResolvedErasureSignature());
        break;
      case 2:
        Assert.assertEquals("SoftReference(T,java.lang.ref.ReferenceQueue<? super T>)", it.getResolvedSignature());
        Assert.assertEquals("SoftReference(java.lang.Object,java.lang.ref.ReferenceQueue)", it.getResolvedErasureSignature());
        break;
      default:
        Assert.fail(("Unexpected constructor: " + it));
        break;
    }
  };
  resolvedOperations.getDeclaredConstructors().forEach(_function);
}
 
Example 10
Source Project: openjdk-8   Source File: ImageCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Entry getEntry(Object key, GraphicsConfiguration config,
                       int w, int h, Object[] args) {
    Entry entry;
    Iterator<SoftReference<Entry>> iter = entries.listIterator();
    while (iter.hasNext()) {
        SoftReference<Entry> ref = iter.next();
        entry = ref.get();
        if (entry == null) {
            // SoftReference was invalidated, remove the entry
            iter.remove();
        }
        else if (entry.equals(config, w, h, args)) {
            // Put most recently used entries at the head
            iter.remove();
            entries.addFirst(ref);
            return entry;
        }
    }
    // Entry doesn't exist
    entry = new Entry(config, w, h, args);
    if (entries.size() >= maxCount) {
        entries.removeLast();
    }
    entries.addFirst(new SoftReference<Entry>(entry));
    return entry;
}
 
Example 11
Source Project: openjdk-8   Source File: TCPTransport.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verify that the given AccessControlContext has permission to
 * accept this connection.
 */
void checkAcceptPermission(SecurityManager sm,
                           AccessControlContext acc)
{
    /*
     * Note: no need to synchronize on cache-related fields, since this
     * method only gets called from the ConnectionHandler's thread.
     */
    if (sm != cacheSecurityManager) {
        okContext = null;
        authCache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = sm;
    }
    if (acc.equals(okContext) || authCache.containsKey(acc)) {
        return;
    }
    InetAddress addr = socket.getInetAddress();
    String host = (addr != null) ? addr.getHostAddress() : "*";

    sm.checkAccept(host, socket.getPort());

    authCache.put(acc, new SoftReference<AccessControlContext>(acc));
    okContext = acc;
}
 
Example 12
Source Project: bt   Source File: BufferManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public BorrowedBuffer<ByteBuffer> borrowByteBuffer() {
    Deque<SoftReference<?>> deque = getReleasedBuffersDeque(ByteBuffer.class);
    SoftReference<ByteBuffer> ref;
    ByteBuffer buffer = null;
    do {
        ref = (SoftReference<ByteBuffer>) deque.pollLast();
        if (ref != null) {
            buffer = ref.get();
        }
        // check if the referenced buffer has been garbage collected
    } while (ref != null && buffer == null);

    if (buffer == null) {
        buffer = ByteBuffer.allocateDirect(bufferSize);
    } else {
        // reset buffer before re-using
        buffer.clear();
    }
    return new DefaultBorrowedBuffer<>(buffer);
}
 
Example 13
Source Project: TencentKona-8   Source File: StrikeCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Reference getStrikeRef(FontStrike strike, boolean weak) {
    /* Some strikes may have no disposer as there's nothing
     * for them to free, as they allocated no native resource
     * eg, if they did not allocate resources because of a problem,
     * or they never hold native resources. So they create no disposer.
     * But any strike that reaches here that has a null disposer is
     * a potential memory leak.
     */
    if (strike.disposer == null) {
        if (weak) {
            return new WeakReference(strike);
        } else {
            return new SoftReference(strike);
        }
    }

    if (weak) {
        return new WeakDisposerRef(strike);
    } else {
        return new SoftDisposerRef(strike);
    }
}
 
Example 14
@SuppressWarnings("unchecked")
protected final Reference<K> getOrCreateReference(final K ctx) {
    if (ctx.reference == null) {
        // Create the reference:
        switch (refType) {
            case REF_HARD:
                ctx.reference = new HardReference<K>(ctx);
                break;
            case REF_SOFT:
                ctx.reference = new SoftReference<K>(ctx);
                break;
            default:
            case REF_WEAK:
                ctx.reference = new WeakReference<K>(ctx);
                break;
        }
    }
    return (Reference<K>) ctx.reference;
}
 
Example 15
private Entry getEntry(Object key, GraphicsConfiguration config,
                       int w, int h, Object[] args) {
    Entry entry;
    Iterator<SoftReference<Entry>> iter = entries.listIterator();
    while (iter.hasNext()) {
        SoftReference<Entry> ref = iter.next();
        entry = ref.get();
        if (entry == null) {
            // SoftReference was invalidated, remove the entry
            iter.remove();
        }
        else if (entry.equals(config, w, h, args)) {
            // Put most recently used entries at the head
            iter.remove();
            entries.addFirst(ref);
            return entry;
        }
    }
    // Entry doesn't exist
    entry = new Entry(config, w, h, args);
    if (entries.size() >= maxCount) {
        entries.removeLast();
    }
    entries.addFirst(new SoftReference<Entry>(entry));
    return entry;
}
 
Example 16
Source Project: jdk8u_jdk   Source File: MethodRef.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
            return null;
        }
        this.methodRef = new SoftReference<>(method);
    }
    return isPackageAccessible(method.getDeclaringClass()) ? method : null;
}
 
Example 17
Source Project: emissary   Source File: ClassLookupCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Look up a class in the cache.
 *
 * @param className The class name to find.
 * @return If the class name is currently known to the cache, the corresponding {@link Class} object is returned.
 *         Otherwise {@code null}.
 */
public static Class<?> get(final String className) {
    // Currently there is at most one cached lookup per thread, so
    // we can just check if the current thread knows about the
    // given class name.
    final SoftReference<NamedClass<?>> softResult = cachedLookupResult.get();
    if (softResult == null) {
        return null; // Nothing is currently cached in this thread.
    }

    final NamedClass<?> actualResult = softResult.get();
    if (actualResult == null) {
        return null; // There was something cached but it's been lost.
    }

    // We do have a cached lookup. It can be used iff it matches
    // the given name.
    return actualResult.getClass(className);
}
 
Example 18
public static BaseFragment getFragment(int pos) {
    BaseFragment fragment = null;
    if (null != arr.get(pos))
        fragment = arr.get(pos).get();
    if (null == fragment) {
        switch (pos) {
            case 0:
                fragment = new MainPageFragment();
                break;
            case 1:
                fragment = new WantingFragment();
                break;
            case 2:
                fragment = new MessageFragment();
                break;
            case 3:
                fragment = new MineFragment();
                break;
        }
        arr.put(0, new SoftReference<BaseFragment>(fragment));
    }
    return fragment;
}
 
Example 19
Source Project: XMPPSample_Studio   Source File: EmojiUtil.java    License: Apache License 2.0 6 votes vote down vote up
private EmojiUtil(Context context) {
	this.context = context;
	density = context.getResources().getDisplayMetrics().density;
	try {
		if (density >= 1.5f) {
			this.isHdpi = true;
			InputStream localInputStream = context.getAssets().open("emoji/emoji_2x.png");
			Options opts = new Options();
			opts.inPurgeable = true;
			opts.inInputShareable = true;
			emojiImages = BitmapFactory.decodeStream(localInputStream, null, opts);
		}
		String[] index = EMOJI_INDEX.split("\n");
		emojiRects = new HashMap<String, Rect>();
		emojiDrawables = new HashMap<String, SoftReference<Drawable>>();
		for (int i = 0; i < index.length; i++) {
			String[] emojis = index[i].split("-");
			for (int j = 0; j < emojis.length; j++) {
				emojiRects.put(emojis[j], new Rect(j * 40, i * 40, 40 * (j + 1), 40 * (i + 1)));
			}
		}
	} catch (IOException localIOException) {

	}
}
 
Example 20
Source Project: JavaRushTasks   Source File: SoftCache.java    License: MIT License 5 votes vote down vote up
public AnyObject remove(Long key) {
    SoftReference<AnyObject> softReference = cacheMap.remove(key);

    //напишите тут ваш код
    if (softReference != null) {
        AnyObject o = softReference.get();
        softReference.clear();
        return o;
    } else {
        return null;
    }
}
 
Example 21
Source Project: openjdk-jdk9   Source File: TCPChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if the current caller has sufficient privilege to make
 * a connection to the remote endpoint.
 * @exception SecurityException if caller is not allowed to use this
 * Channel.
 */
private void checkConnectPermission() throws SecurityException {
    SecurityManager security = System.getSecurityManager();
    if (security == null)
        return;

    if (security != cacheSecurityManager) {
        // The security manager changed: flush the cache
        okContext = null;
        authcache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = security;
    }

    AccessControlContext ctx = AccessController.getContext();

    // If ctx is the same context as last time, or if it
    // appears in the cache, bypass the checkConnect.
    if (okContext == null ||
        !(okContext.equals(ctx) || authcache.containsKey(ctx)))
    {
        security.checkConnect(ep.getHost(), ep.getPort());
        authcache.put(ctx, new SoftReference<AccessControlContext>(ctx));
        // A WeakHashMap is transformed into a SoftHashSet by making
        // each value softly refer to its own key (Peter's idea).
    }
    okContext = ctx;
}
 
Example 22
Source Project: hottub   Source File: MethodTypeForm.java    License: GNU General Public License v2.0 5 votes vote down vote up
synchronized public LambdaForm setCachedLambdaForm(int which, LambdaForm form) {
    // Simulate a CAS, to avoid racy duplication of results.
    SoftReference<LambdaForm> entry = lambdaForms[which];
    if (entry != null) {
        LambdaForm prev = entry.get();
        if (prev != null) {
            return prev;
        }
    }
    lambdaForms[which] = new SoftReference<>(form);
    return form;
}
 
Example 23
Source Project: hottub   Source File: AquaUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
T get() {
    T referent;
    if (objectRef != null && (referent = objectRef.get()) != null) return referent;
    referent = create();
    objectRef = new SoftReference<T>(referent);
    return referent;
}
 
Example 24
Source Project: JDKSourceCode1.8   Source File: DateTimeFormatterBuilder.java    License: MIT License 5 votes vote down vote up
private String getDisplayName(String id, int type, Locale locale) {
    if (textStyle == TextStyle.NARROW) {
        return null;
    }
    String[] names;
    SoftReference<Map<Locale, String[]>> ref = cache.get(id);
    Map<Locale, String[]> perLocale = null;
    if (ref == null || (perLocale = ref.get()) == null ||
        (names = perLocale.get(locale)) == null) {
        names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
        if (names == null) {
            return null;
        }
        names = Arrays.copyOfRange(names, 0, 7);
        names[5] =
            TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale);
        if (names[5] == null) {
            names[5] = names[0]; // use the id
        }
        names[6] =
            TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale);
        if (names[6] == null) {
            names[6] = names[0];
        }
        if (perLocale == null) {
            perLocale = new ConcurrentHashMap<>();
        }
        perLocale.put(locale, names);
        cache.put(id, new SoftReference<>(perLocale));
    }
    switch (type) {
    case STD:
        return names[textStyle.zoneNameStyleIndex() + 1];
    case DST:
        return names[textStyle.zoneNameStyleIndex() + 3];
    }
    return names[textStyle.zoneNameStyleIndex() + 5];
}
 
Example 25
private XMLParserConfiguration initialize() {
    XML11Configuration config = new XML11Configuration();
    if (fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        config.setProperty(SECURITY_MANAGER, new XMLSecurityManager());
    }
    config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER));
    config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER));
    XMLErrorReporter errorReporter = (XMLErrorReporter) fComponentManager.getProperty(ERROR_REPORTER);
    config.setProperty(ERROR_REPORTER, errorReporter);
    // add message formatters
    if (errorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) {
        XMLMessageFormatter xmft = new XMLMessageFormatter();
        errorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft);
        errorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft);
    }
    config.setProperty(SYMBOL_TABLE, fComponentManager.getProperty(SYMBOL_TABLE));
    config.setProperty(VALIDATION_MANAGER, fComponentManager.getProperty(VALIDATION_MANAGER));
    config.setDocumentHandler(fSchemaValidator);
    config.setDTDHandler(null);
    config.setDTDContentModelHandler(null);
    config.setProperty(Constants.XML_SECURITY_PROPERTY_MANAGER,
            fComponentManager.getProperty(Constants.XML_SECURITY_PROPERTY_MANAGER));
    config.setProperty(Constants.SECURITY_MANAGER,
            fComponentManager.getProperty(Constants.SECURITY_MANAGER));
    fConfiguration = new SoftReference(config);
    return config;
}
 
Example 26
Source Project: ProjectStudy   Source File: T02_SoftReference.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    // 分配了20M
    SoftReference<byte[]> softReference = new SoftReference<>(new byte[1024 * 1024 * 10]);
    System.out.println(softReference.get());
    System.gc();
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(softReference.get());
    // 再分配一个12M数组,heap将装不下,这时候系统会垃圾回收,先回收一次,如果不够,会把软引用干掉
    byte[] b = new byte[1024 * 1024 * 12];
    System.out.println(softReference.get());
}
 
Example 27
Source Project: dragonwell8_jdk   Source File: MethodRef.java    License: GNU General Public License v2.0 5 votes vote down vote up
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.getDeclaringClass());
    }
}
 
Example 28
private String getDisplayName(String id, int type, Locale locale) {
    if (textStyle == TextStyle.NARROW) {
        return null;
    }
    String[] names;
    SoftReference<Map<Locale, String[]>> ref = cache.get(id);
    Map<Locale, String[]> perLocale = null;
    if (ref == null || (perLocale = ref.get()) == null ||
        (names = perLocale.get(locale)) == null) {
        names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
        if (names == null) {
            return null;
        }
        names = Arrays.copyOfRange(names, 0, 7);
        names[5] =
            TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale);
        if (names[5] == null) {
            names[5] = names[0]; // use the id
        }
        names[6] =
            TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale);
        if (names[6] == null) {
            names[6] = names[0];
        }
        if (perLocale == null) {
            perLocale = new ConcurrentHashMap<>();
        }
        perLocale.put(locale, names);
        cache.put(id, new SoftReference<>(perLocale));
    }
    switch (type) {
    case STD:
        return names[textStyle.zoneNameStyleIndex() + 1];
    case DST:
        return names[textStyle.zoneNameStyleIndex() + 3];
    }
    return names[textStyle.zoneNameStyleIndex() + 5];
}
 
Example 29
Source Project: jdk8u_jdk   Source File: MethodTypeForm.java    License: GNU General Public License v2.0 5 votes vote down vote up
synchronized public MethodHandle setCachedMethodHandle(int which, MethodHandle mh) {
    // Simulate a CAS, to avoid racy duplication of results.
    SoftReference<MethodHandle> entry = methodHandles[which];
    if (entry != null) {
        MethodHandle prev = entry.get();
        if (prev != null) {
            return prev;
        }
    }
    methodHandles[which] = new SoftReference<>(mh);
    return mh;
}
 
Example 30
Source Project: TencentKona-8   Source File: ZoneInfoFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static byte[] getZoneInfoOldMappings() {
    byte[] data;
    SoftReference<byte[]> cache = zoneInfoMappings;
    if (cache != null) {
        data = cache.get();
        if (data != null) {
            return data;
        }
    }
    data = readZoneInfoFile(JAVAZM_FILE_NAME);
    if (data == null) {
        throw new RuntimeException("ZoneInfoOldMapping " +
            JAVAZM_FILE_NAME + " either doesn't exist or doesn't have data");
    }

    int index;
    for (index = 0; index < JAVAZM_LABEL.length; index++) {
        if (data[index] != JAVAZM_LABEL[index]) {
            System.err.println("ZoneInfoOld: wrong magic number: " + JAVAZM_FILE_NAME);
            return null;
        }
    }
    if (data[index++] > JAVAZM_VERSION) {
        System.err.println("ZoneInfoOld: incompatible version ("
                           + data[index - 1] + "): " + JAVAZM_FILE_NAME);
        return null;
    }

    zoneInfoMappings = new SoftReference<>(data);
    return data;
}