Example usage for java.lang System identityHashCode

List of usage examples for java.lang System identityHashCode

Introduction

In this page you can find the example usage for java.lang System identityHashCode.

Prototype

@HotSpotIntrinsicCandidate
public static native int identityHashCode(Object x);

Source Link

Document

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

Usage

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

private ContributionDef createContributionToMasterObjectProvider() {

    return new AbstractContributionDef() {
        @Override/*from   w  ww .j  a v a 2  s  . c  o  m*/
        public String getServiceId() {
            return "MasterObjectProvider";
        }

        @Override
        public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
                OrderedConfiguration configuration) {
            final OperationTracker tracker = resources.getTracker();

            final ApplicationContext context = resources.getService(SERVICE_ID, ApplicationContext.class);

            //region CUSTOMIZATION
            final ObjectProvider springBeanProvider = new ObjectProvider() {
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {

                    try {
                        T bean = context.getBean(objectType);
                        if (!objectType.isInterface()) {
                            return bean;
                        }
                        // We proxify here because Tapestry calls toString method on proxy, which realizes the underlying service, with scope issues
                        return (T) Proxy.newProxyInstance(objectType.getClassLoader(),
                                new Class<?>[] { objectType }, new AbstractInvocationHandler() {
                                    @Override
                                    protected Object handleInvocation(Object proxy, Method method,
                                            Object[] args) throws Throwable {
                                        String methodName = method.getName();
                                        if (methodName.equals("equals")) {
                                            // Only consider equal when proxies are identical.
                                            return (proxy == args[0]);
                                        }
                                        if (methodName.equals("hashCode")) {
                                            // Use hashCode of proxy.
                                            return System.identityHashCode(proxy);
                                        }
                                        if (methodName.equals("toString")) {
                                            return "Current Spring " + objectType.getSimpleName();
                                        }
                                        try {
                                            return method.invoke(bean, args);
                                        } catch (InvocationTargetException e) {
                                            throw e.getCause();
                                        }
                                    }
                                });

                    } catch (NoUniqueBeanDefinitionException e) {
                        String message = String.format(
                                "Spring context contains %d beans assignable to type %s.",
                                e.getNumberOfBeansFound(), PlasticUtils.toTypeName(objectType));

                        throw new IllegalArgumentException(message, e);
                    } catch (NoSuchBeanDefinitionException e) {
                        return null;
                    }
                }
            };
            //endregion

            final ObjectProvider springBeanProviderInvoker = new ObjectProvider() {
                @Override
                public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
                        final ObjectLocator locator) {
                    return tracker.invoke("Resolving dependency by searching Spring ApplicationContext",
                            () -> springBeanProvider.provide(objectType, annotationProvider, locator));
                }
            };

            ObjectProvider outerCheck = new ObjectProvider() {
                @Override
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {
                    // I think the following line is the only reason we put the
                    // SpringBeanProvider here,
                    // rather than in SpringModule.

                    if (!applicationContextCreated.get())
                        return null;

                    return springBeanProviderInvoker.provide(objectType, annotationProvider, locator);
                }
            };

            configuration.add("SpringBean", outerCheck, "after:AnnotationBasedContributions",
                    "after:ServiceOverride");
        }
    };
}

From source file:org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluator.java

@Override
public void evaluate(RangerAccessRequest request, RangerDataMaskResult result) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
    }//from   www .ja  va2s. com

    RangerPerfTracer perf = null;

    if (RangerPerfTracer.isPerfTraceEnabled(PERF_POLICY_REQUEST_LOG)) {
        perf = RangerPerfTracer.getPerfTracer(PERF_POLICY_REQUEST_LOG,
                "RangerPolicyEvaluator.evaluate(requestHashCode="
                        + Integer.toHexString(System.identityHashCode(request)) + "," + perfTag + ")");
    }

    if (request != null && result != null && CollectionUtils.isNotEmpty(dataMaskEvaluators)) {

        if (!result.getIsAccessDetermined() || !result.getIsAuditedDetermined()) {
            RangerPolicyResourceMatcher.MatchType matchType = resourceMatcher != null
                    ? resourceMatcher.getMatchType(request.getResource(), request.getContext())
                    : RangerPolicyResourceMatcher.MatchType.NONE;

            final boolean isMatched;
            if (request.isAccessTypeAny()) {
                isMatched = matchType != RangerPolicyResourceMatcher.MatchType.NONE;
            } else if (request
                    .getResourceMatchingScope() == RangerAccessRequest.ResourceMatchingScope.SELF_OR_DESCENDANTS) {
                isMatched = matchType == RangerPolicyResourceMatcher.MatchType.SELF
                        || matchType == RangerPolicyResourceMatcher.MatchType.DESCENDANT;
            } else {
                isMatched = matchType == RangerPolicyResourceMatcher.MatchType.SELF
                        || matchType == RangerPolicyResourceMatcher.MatchType.ANCESTOR;
            }

            if (isMatched) {
                if (!result.getIsAuditedDetermined()) {
                    if (isAuditEnabled()) {
                        result.setIsAudited(true);
                        result.setAuditPolicyId(getPolicy().getId());
                    }
                }
                if (!result.getIsAccessDetermined()) {
                    if (hasMatchablePolicyItem(request)) {
                        evaluatePolicyItems(request, result);
                    }
                }
            }
        }

    }

    RangerPerfTracer.log(perf);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
    }
}

From source file:IK.AbstractBone.java

public AbstractBone(AbstractArmature parArma, DVector tipHeading, DVector rollHeading, String inputTag,
        frameType coordinateType) throws NullParentForBoneException {

    if (parArma != null) {
        if (this.tag == null || this.tag == "") {
            this.tag = Integer.toString(System.identityHashCode(this));
        } else/* w ww .j a  v  a2s .  com*/
            this.tag = inputTag;

        Ray tipHeadingRay = new Ray(parArma.localAxes.origin(), tipHeading);
        Ray rollHeadingRay = new Ray(parArma.localAxes.origin(), rollHeading);
        DVector tempTip = new DVector();
        DVector tempRoll = new DVector();
        DVector tempX = new DVector();

        if (coordinateType == frameType.GLOBAL) {
            tempTip = tipHeadingRay.heading();
            tempRoll = rollHeadingRay.heading();
        } else if (coordinateType == frameType.RELATIVE) {
            tempTip = parArma.localAxes.getGlobalOf(tipHeadingRay.heading());
            tempRoll = parArma.localAxes.getGlobalOf(rollHeadingRay.heading());
        } else {
            System.out.println("WOAH WOAH WOAH");
        }

        tempX = tempRoll.cross(tempTip);
        tempRoll = tempX.cross(tempTip);

        this.boneHeight = tipHeading.mag();
        this.parentArmature = parArma;

        generateAxes(parentArmature.localAxes.origin(), tempX, tempTip, tempRoll);
        this.localAxes.orthogonalize();
        localAxes.setParent(parentArmature.localAxes);
        previousOrientation = localAxes.attachedCopy(true);

        majorRotationAxes = parentArmature.localAxes().getAbsoluteCopy();
        majorRotationAxes.setParent(parent.localAxes);

        parentArmature.addToBoneList(this);
        //this.updateSegmentedArmature();   

    } else {
        throw new NullParentForBoneException();
    }

}

From source file:org.droid2droid.internal.AbstractRemoteAndroidImpl.java

@Override
public boolean bindService(final Intent service, final ServiceConnection conn, final int flags) {

    new AsyncTask<Void, Void, Void>() {
        @Override//from   w w w .j  a v a2  s.c o  m
        protected Void doInBackground(Void... v) {
            try {
                ComponentName[] name = new ComponentName[1];
                int oid = bindOID(getConnectionId(), System.identityHashCode(conn), service, flags, name,
                        mExecuteTimeout);
                if (oid == -1)
                    PostTools.postServiceDisconnected(conn, name[0]);
                else {
                    RemoteBinderProxy proxy = new RemoteBinderProxy(AbstractRemoteAndroidImpl.this, oid);
                    Binded disconnect = new Binded();
                    disconnect.name = name[0];
                    disconnect.conn = conn;
                    disconnect.proxy = proxy;
                    synchronized (mBinders) {
                        mBinders.put(conn, disconnect);
                    }
                    PostTools.postServiceConnected(conn, name[0], proxy);
                }
            } catch (SecurityException e) {
                if (E)
                    Log.e(TAG_SECURITY, PREFIX_LOG + "Refuse connexion", e);
                close();
            } catch (RemoteException e) {
                PostTools.postServiceDisconnected(conn, null); // FIXME: null en ComponentName ?
            }
            return null;
        }
    }.execute();
    return true;
}

From source file:WeakIdentityMap.java

public V put(K key, V value) {
    if (key == null) {
        key = (K) KeyFactory.NULL;
    }// w  w w.  j  av  a2s . c  om

    cleanup();

    // Make sure the key is not already in the WeakIdentityMap.
    Entry[] tab = this.table;
    int hash = System.identityHashCode(key);
    int index = (hash & 0x7fffffff) % tab.length;

    for (Entry e = tab[index], prev = null; e != null; e = e.next) {
        Object entryKey = e.get();

        if (entryKey == null) {
            // Clean up after a cleared Reference.
            this.modCount++;
            if (prev != null) {
                prev.next = e.next;
            } else {
                tab[index] = e.next;
            }
            this.count--;
        } else if (e.hash == hash && key == entryKey) {
            Object old = e.value;
            e.value = value;
            return (V) old;
        } else {
            prev = e;
        }
    }

    this.modCount++;

    if (this.count >= this.threshold) {
        // Rehash the table if the threshold is still exceeded.
        rehash();
        tab = this.table;
        index = (hash & 0x7fffffff) % tab.length;
    }

    // Creates the new entry.
    Entry e = new Entry(hash, key, this.queue, value, tab[index]);
    tab[index] = e;
    this.count++;
    return null;
}

From source file:ConcurrentReferenceHashMap.java

private int hashOf(Object key) {
    return hash(identityComparisons ? System.identityHashCode(key) : key.hashCode());
}

From source file:org.eclipse.gyrex.cloud.internal.preferences.ZooKeeperBasedPreferences.java

private ZooKeeperBasedPreferences createChild(final String name, final List<ZooKeeperBasedPreferences> added) {
    // prevent concurrent modification
    childrenModifyLock.lock();//from  ww  w.j  av a 2s . c  o m
    try {
        // create child only if necessary
        ZooKeeperBasedPreferences child = children.get(name);
        if (null != child) {
            return child;
        }

        // create new child
        child = newChild(name);
        final ZooKeeperBasedPreferences existingChild = children.put(name, child);
        if ((null != existingChild) && (existingChild != child)) {
            // this shouldn't happen (because of the lock)
            // but let's be really sure
            throw new AssertionError(String.format(
                    "programming/concurrency error: created a new child although one still existed (new=%s %d) (old=%s %d)",
                    child, System.identityHashCode(child), existingChild,
                    System.identityHashCode(existingChild)));
        }

        // log message
        if (CloudDebug.zooKeeperPreferences) {
            LOG.debug("Node {} child created: {} ", this, name);
        }

        // register with service
        service.activateNode(child);

        // remove from pending removals list
        pendingChildRemovals.remove(name);

        // trigger event
        if (null != added) {
            added.add(child);
        }
        return child;
    } finally {
        childrenModifyLock.unlock();
    }
}

From source file:org.jboss.jopr.tool.jbas5.MetadataConversionUtils.java

private static PropertyDefinitionMap convertMetaTypeToPropertyDefinitionMap(MetaType metaType, String name,
        MetaValue metaValue) {/*from w ww.j  av a 2  s . c  o m*/
    PropertyDefinitionMap propDefMap = new PropertyDefinitionMap(name, null, false);
    if (metaType.isComposite()) {
        if (!(metaType instanceof MapCompositeMetaType)) {
            CompositeMetaType compositeMetaType = (CompositeMetaType) metaType;
            for (String itemName : compositeMetaType.itemSet()) {
                MetaType itemMetaType = compositeMetaType.getType(itemName);
                if (itemMetaType.isComposite()) {
                    // Avoid StackOverflowErrors caused by recursive CompositeMetaType metadata.
                    if (itemMetaType == compositeMetaType)
                        LOG.error("CompositeMetaType " + compositeMetaType
                                + " contains an item whose type is a reference to the CompositeMetaType itself!");
                    else
                        LOG.error("CompositeMetaType " + compositeMetaType
                                + " contains an item whose type is another CompositeMetaType: " + itemMetaType);
                    continue;
                }
                LOG.trace("Converting item with type [" + itemMetaType + "@"
                        + System.identityHashCode(itemMetaType) + "] and name [" + itemName + "]...");
                PropertyDefinition itemPropDef = convertMetaTypeToPropertyDefinition(itemMetaType, itemName,
                        null);
                propDefMap.put(itemPropDef);
                String desc = (!itemName.equals(compositeMetaType.getDescription(itemName)))
                        ? compositeMetaType.getDescription(itemName)
                        : null;
                itemPropDef.setDescription(desc);
            }
        }
    } else if (metaType.isGeneric()) {
        if (metaValue != null) {
            GenericValue genericValue = (GenericValue) metaValue;
            Serializable value = genericValue.getValue();
            if (value != null && value instanceof ManagedObject) {
                ManagedObject managedObject = (ManagedObject) value;
                for (ManagedProperty managedProp : managedObject.getProperties().values()) {
                    PropertyDefinition itemPropDef = convertManagedPropertyToPropertyDefinition(managedProp);
                    propDefMap.put(itemPropDef);
                }
            }
        }
    } else if (metaType.isTable()) {
        TableMetaType tableMetaType = (TableMetaType) metaType;
        CompositeMetaType itemMetaType = tableMetaType.getRowType();
        for (String itemName : tableMetaType.getIndexNames()) {
            PropertyDefinition itemPropDef = convertMetaTypeToPropertyDefinition(itemMetaType, itemName, null);
            propDefMap.put(itemPropDef);
        }
    } else if (metaType instanceof PropertiesMetaType) {
        @SuppressWarnings({ "UnusedDeclaration" })
        PropertiesMetaType propertiesMetaType = (PropertiesMetaType) metaType;
    }
    return propDefMap;
}

From source file:de.ailis.midi4js.Midi4JS.java

/**
 * Returns all currently open transmitters.
 *
 * @param deviceHandle/*w w w. j  a v a  2 s  . c o m*/
 *            The device handle.
 * @return All currently open transmitters in form of a JSON-encoded string
 *         which describes an array of transmitter handles.
 * @throws JSONException
 *             When JSON data could not be constructed.
 */
public String getTransmitters(final int deviceHandle) throws JSONException {
    final MidiDevice device = resolveDeviceHandle(deviceHandle);
    final JSONStringer json = new JSONStringer();
    json.array();
    for (final Transmitter transmitter : device.getTransmitters()) {
        json.value(System.identityHashCode(transmitter));
    }
    json.endArray();
    return json.toString();
}

From source file:com.netflix.governator.lifecycle.LifecycleManager.java

private void stopInstances() throws Exception {
    for (PreDestroyRecord record : getReversed(preDestroys)) {
        log.debug(String.format("Stopping %s:%d", record.obj.getClass().getName(),
                System.identityHashCode(record.obj)));
        setState(record.obj, LifecycleState.PRE_DESTROYING);

        for (Method preDestroy : record.preDestroyMethods) {
            log.debug(String.format("\t%s()", preDestroy.getName()));
            try {
                preDestroy.invoke(record.obj);
            } catch (Throwable e) {
                log.error("Couldn't stop lifecycle managed instance", e);
            }//  w w  w . j  a v  a 2 s  .  c o m
        }

        objectStates.remove(new StateKey(record.obj));
    }
}