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:net.algart.simagis.imageio.IIOMetadataToJsonConverter.java

private JSONObject iioNodeUserObjectToJson(IIOMetadataNode node) throws JSONException {
    final Object userObject = node.getUserObject();
    if (userObject == null) {
        return null;
    }// www.  j  av a  2 s  . c o  m
    JSONObject result = new JSONObject();
    result.put("class", userObject.getClass().getCanonicalName());
    final String stringRepresentation = userObject.toString();
    final String javaDefaultStringRepresentation = userObject.getClass().getName() + "@"
            + Integer.toHexString(System.identityHashCode(userObject)); // see JavaDoc to Object.toString
    if (!stringRepresentation.equals(javaDefaultStringRepresentation)) {
        // so, we can hope for some non-trivial information in toString()
        result.put("toString", stringRepresentation);
    }
    if (userObject instanceof byte[]) {
        byte[] bytes = (byte[]) userObject;
        result.put("valueLength", bytes.length);
        if (bytes.length <= 16384) {
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < bytes.length; k++) {
                // formatting bytes like it is done in TIFFUndefined value in TIFF metadata
                if (k > 0) {
                    sb.append(",");
                }
                sb.append(bytes[k] & 0xFF);
            }
            result.put("valueBytes", sb.toString());
        }
    }
    JSONObject extendedInfo;
    try {
        extendedInfo = extendedUserObjectToJson(userObject);
    } catch (Exception e) {
        extendedInfo = exceptionToJson(e);
    }
    result.put("extendedInfo", extendedInfo);
    return result;
}

From source file:com.meidusa.venus.client.RemotingInvocationHandler.java

protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method,
        EndpointParameter[] params, Object[] args) throws Exception {
    String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint);

    AthenaTransactionId athenaTransactionId = null;
    if (service.athenaFlag()) {
        athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName);
    }//from w ww. ja  v  a2s .  c  om
    boolean async = false;

    if (endpoint.async()) {
        async = true;
    }

    byte[] traceID = VenusTracerUtil.getTracerID();

    if (traceID == null) {
        traceID = VenusTracerUtil.randomTracerID();
    }

    Serializer serializer = SerializerFactory.getSerializer(serializeType);

    SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null);

    serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID;
    serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement();
    serviceRequestPacket.traceId = traceID;
    serviceRequestPacket.apiName = apiName;
    serviceRequestPacket.serviceVersion = service.version();
    serviceRequestPacket.parameterMap = new HashMap<String, Object>();

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (args[i] instanceof InvocationListener) {
                async = true;
                ReferenceInvocationListener listener = new ReferenceInvocationListener();
                ServicePacketBuffer buffer = new ServicePacketBuffer(16);
                buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8");
                buffer.writeInt(System.identityHashCode(args[i]));
                listener.setIdentityData(buffer.toByteBuffer().array());
                Type type = method.getGenericParameterTypes()[i];
                if (type instanceof ParameterizedType) {
                    ParameterizedType genericType = ((ParameterizedType) type);
                    container.putInvocationListener((InvocationListener) args[i],
                            genericType.getActualTypeArguments()[0]);
                } else {
                    throw new InvalidParameterException("invocationListener is not generic");
                }

                serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener);
            } else {
                serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]);
            }

        }
    }
    setTransactionId(serviceRequestPacket, athenaTransactionId);

    PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class);
    long start = TimeUtil.currentTimeMillis();
    long borrowed = start;

    if (async) {
        if (!this.isEnableAsync()) {
            throw new VenusConfigException("service async call disabled");
        }

        BackendConnection conn = null;
        try {

            if (nioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = nioConnPool.borrowObject();
            }
            borrowed = TimeUtil.currentTimeMillis();

            conn.write(serviceRequestPacket.toByteBuffer());
            VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                    JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
            return null;
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            if (performanceLogger.isDebugEnabled()) {
                long end = TimeUtil.currentTimeMillis();
                long time = end - borrowed;
                StringBuffer buffer = new StringBuffer();
                buffer.append("[").append(borrowed - start).append(",").append(time)
                        .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=")
                        .append(serviceRequestPacket.apiName);

                performanceLogger.debug(buffer.toString());
            }

            if (conn != null) {
                nioConnPool.returnObject(conn);
            }
        }
    } else {
        AbstractBIOConnection conn = null;
        int soTimeout = 0;
        int oldTimeout = 0;
        boolean success = true;
        int errorCode = 0;
        AbstractServicePacket packet = null;
        String remoteAddress = null;
        boolean invalided = false;
        try {
            if (bioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = (AbstractBIOConnection) bioConnPool.borrowObject();
            }
            remoteAddress = conn.getRemoteAddress();
            borrowed = TimeUtil.currentTimeMillis();
            ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass());

            oldTimeout = conn.getSoTimeout();
            if (config != null) {
                EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name());
                if (endpointConfig != null) {
                    int eTimeOut = endpointConfig.getTimeWait();
                    if (eTimeOut > 0) {
                        soTimeout = eTimeOut;
                    }
                } else {
                    if (config.getTimeWait() > 0) {
                        soTimeout = config.getTimeWait();
                    } else {
                        if (endpoint.timeWait() > 0) {
                            soTimeout = endpoint.timeWait();
                        }
                    }
                }

            } else {

                if (endpoint.timeWait() > 0) {
                    soTimeout = endpoint.timeWait();
                }
            }

            byte[] bts;

            try {

                if (soTimeout > 0) {
                    conn.setSoTimeout(soTimeout);
                }
                conn.write(serviceRequestPacket.toByteArray());
                VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                        JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                bts = conn.read();
            } catch (IOException e) {
                try {
                    conn.close();
                } catch (Exception e1) {
                    // ignore
                }

                bioConnPool.invalidateObject(conn);
                invalided = true;
                Class<?>[] eClass = method.getExceptionTypes();

                if (eClass != null && eClass.length > 0) {
                    for (Class<?> clazz : eClass) {
                        if (e.getClass().isAssignableFrom(clazz)) {
                            throw e;
                        }
                    }
                }

                throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp="
                        + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e);
            }

            int type = AbstractServicePacket.getType(bts);
            switch (type) {
            case PacketConstant.PACKET_TYPE_ERROR:
                ErrorPacket error = new ErrorPacket();
                error.init(bts);
                packet = error;
                Exception e = venusExceptionFactory.getException(error.errorCode, error.message);
                if (e == null) {
                    throw new DefaultVenusException(error.errorCode, error.message);
                } else {
                    if (error.additionalData != null) {
                        Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class);
                        if (tmap != null && tmap.size() > 0) {
                            Object obj = serializer.decode(error.additionalData, tmap);
                            BeanUtils.copyProperties(e, obj);
                        }
                    }
                    throw e;
                }
            case PacketConstant.PACKET_TYPE_OK:
                OKPacket ok = new OKPacket();
                ok.init(bts);
                packet = ok;
                return null;
            case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE:
                ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer,
                        method.getGenericReturnType());
                response.init(bts);
                packet = response;
                return response.result;
            default: {
                logger.warn("unknow response type=" + type);
                success = false;
                return null;
            }
            }
        } catch (Exception e) {
            success = false;

            if (e instanceof CodedException
                    || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0
                    || e instanceof RuntimeException) {
                if (e instanceof CodedException) {
                    errorCode = ((CodedException) e).getErrorCode();
                }
                throw e;
            } else {
                RemoteException code = e.getClass().getAnnotation(RemoteException.class);
                if (code != null) {
                    errorCode = code.errorCode();
                    throw e;
                } else {
                    ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class);
                    if (eCode != null) {
                        errorCode = eCode.errorCode();
                        throw e;
                    } else {
                        errorCode = -1;
                        if (conn == null) {
                            throw new DefaultVenusException(e.getMessage(), e);
                        } else {
                            throw new DefaultVenusException(
                                    e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e);
                        }
                    }
                }
            }
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            long end = TimeUtil.currentTimeMillis();
            long time = end - borrowed;
            StringBuffer buffer = new StringBuffer();
            buffer.append("[").append(borrowed - start).append(",").append(time)
                    .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=")
                    .append(serviceRequestPacket.apiName);
            if (remoteAddress != null) {
                buffer.append(", remote=").append(remoteAddress);
            } else {
                buffer.append(", pool=").append(bioConnPool.toString());
            }
            buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=")
                    .append(serviceRequestPacket.clientRequestId);

            if (packet != null) {
                if (packet instanceof ErrorPacket) {
                    buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode);
                    buffer.append(", message=").append(((ErrorPacket) packet).message);
                } else {
                    buffer.append(", errorCode=0");
                }
            }

            if (pLevel != null) {

                if (pLevel.printParams()) {
                    buffer.append(", params=");
                    buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                }

                if (time > pLevel.error() && pLevel.error() > 0) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time > pLevel.warn() && pLevel.warn() > 0) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time > pLevel.info() && pLevel.info() > 0) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            } else {
                buffer.append(", params=");
                buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));

                if (time >= 30 * 1000) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time >= 10 * 1000) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time >= 5 * 1000) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            }

            if (conn != null && !invalided) {
                if (!conn.isClosed() && soTimeout > 0) {
                    conn.setSoTimeout(oldTimeout);
                }
                bioConnPool.returnObject(conn);
            }

        }
    }
}

From source file:de.micromata.genome.util.strings.ReducedReflectionToStringBuilder.java

@Override
public ToStringBuilder appendAsObjectToString(Object object) {
    this.getStringBuffer().append(object.getClass().getSimpleName()).append('@')
            .append(Integer.toHexString(System.identityHashCode(object)));
    if (object instanceof ShortDisplayable) {
        this.getStringBuffer().append("[").append(((ShortDisplayable) object).toShortString()).append("]");
    }/* w  ww . j  a v a2 s. c  om*/
    return this;
}

From source file:org.apache.ranger.policyengine.RangerPolicyEnginePerformanceTest.java

@Test
public void policyEngineTest() throws InterruptedException {
    List<RangerAccessRequest> requests = requestsCache.getUnchecked(concurrency);
    ServicePolicies servicePolicies = servicePoliciesCache.getUnchecked(numberOfPolicies);

    final RangerPolicyEngineImpl rangerPolicyEngine = new RangerPolicyEngineImpl("perf-test", servicePolicies,
            RangerPolicyFactory.createPolicyEngineOption());
    rangerPolicyEngine.preProcess(requests);

    for (int iterations = 0; iterations < WARM_UP__ITERATIONS; iterations++) {
        // using return value of 'isAccessAllowed' with a cheap operation: System#identityHashCode so JIT wont remove it as dead code
        System.identityHashCode(
                rangerPolicyEngine.isAccessAllowed(requests.get(iterations % concurrency), null));
        PerfDataRecorder.clearStatistics();
    }//from   w  ww.  j  a  v a  2s  . c o m

    final CountDownLatch latch = new CountDownLatch(concurrency);
    for (int i = 0; i < concurrency; i++) {
        final RangerAccessRequest rangerAccessRequest = requests.get(i);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.identityHashCode(rangerPolicyEngine.isAccessAllowed(rangerAccessRequest, null));
                latch.countDown();
            }
        }, String.format("Client #%s", i)).start();
    }
    latch.await();
}

From source file:org.betaconceptframework.astroboa.cache.DefinitionCacheManager.java

private void printDefinitions(Map<String, CmsDefinition> cmsPropertyDefinitions, int depth, StringBuilder sb) {

    String tabs = generateTabs(depth);

    if (MapUtils.isNotEmpty(cmsPropertyDefinitions)) {
        for (CmsDefinition def : cmsPropertyDefinitions.values()) {

            sb.append(tabs).append(def.getName()).append(", instance ").append(System.identityHashCode(def));

            if (def instanceof ContentObjectTypeDefinition) {
                printPropertyDefinitions(((ContentObjectTypeDefinition) def).getPropertyDefinitions(),
                        depth + 1, sb);//from   ww w .ja va 2s.  c om
            } else if (def instanceof ComplexCmsPropertyDefinition) {
                printPropertyDefinitions(((ComplexCmsPropertyDefinition) def).getChildCmsPropertyDefinitions(),
                        depth + 1, sb);
            }
        }
    }

}

From source file:org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsTransaction.java

@Override
public String toString() {
    int ihc = System.identityHashCode(this);
    String ihcString = String.format("0x%s", Hex.bytesToHex((byte) (ihc >>> 24 & 0x000000FF),
            (byte) (ihc >>> 16 & 0x000000FF), (byte) (ihc >>> 8 & 0x000000FF), (byte) (ihc & 0x000000FF)));
    return StringFactory.graphString(this, ihcString);
}

From source file:gdsc.smlm.ij.plugins.EMGainAnalysis.java

/**
 * Randomly generate a histogram from poisson-gamma-gaussian samples
 * //ww w. j  ava 2  s  .c  om
 * @return The histogram
 */
private int[] simulateFromPoissonGammaGaussian() {
    // Randomly sample
    RandomGenerator random = new Well44497b(System.currentTimeMillis() + System.identityHashCode(this));

    PoissonDistribution poisson = new PoissonDistribution(random, _photons, PoissonDistribution.DEFAULT_EPSILON,
            PoissonDistribution.DEFAULT_MAX_ITERATIONS);

    CustomGammaDistribution gamma = new CustomGammaDistribution(random, _photons, _gain,
            GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);

    final int steps = simulationSize;
    int[] sample = new int[steps];
    for (int n = 0; n < steps; n++) {
        if (n % 64 == 0)
            IJ.showProgress(n, steps);

        // Poisson
        double d = poisson.sample();

        // Gamma
        if (d > 0) {
            gamma.setShapeUnsafe(d);
            d = gamma.sample();
        }

        // Gaussian
        d += _noise * random.nextGaussian();

        // Convert the sample to a count 
        sample[n] = (int) Math.round(d + _bias);
    }

    int max = Maths.max(sample);
    int[] h = new int[max + 1];
    for (int s : sample)
        h[s]++;
    return h;
}

From source file:com.microsoft.tfs.client.common.ui.framework.runnable.DeferredProgressMonitorDialogContext.java

private Job createProgressUIJob(final IRunnableWithProgress inputRunnable,
        final RunnableWithProgressWrapper wrappedRunnable, final ProgressMonitorDialog dialog) {
    return new Job("") //$NON-NLS-1$
    {//from   ww w .  ja v  a2 s  . co  m
        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    setUserInterfaceActive(true);

                    /*
                     * Note that this job is executed regardless of whether
                     * the command is still executing. If it has finished,
                     * the progress monitor dialog will be disposed (and
                     * getShell will return null.)
                     */
                    if (dialog.getShell() != null) {
                        /*
                         * Attempt to avoid a UI hang problem. If there is
                         * already a modal Shell, opening the progress
                         * monitor will result in multiple modal Shells.
                         * Note that this cannot be avoided with a
                         * parent-child relationship on all window managers.
                         *
                         * If this occurs, reschedule this deferred runnable
                         * for another interval of the deferTimeMillis. The
                         * blocking dialog may have been removed in this
                         * time (eg, in the case of an authentication
                         * dialog.)
                         */
                        final Shell blocker = ShellUtils.getModalBlockingShell(dialog.getShell());
                        if (blocker != null) {
                            final String messageFormat = "unsafe modal operation - shell [{0} ({1})] for [{2}] blocked by shell [{3} ({4})]"; //$NON-NLS-1$
                            final String message = MessageFormat.format(messageFormat, dialog.getShell(),
                                    Integer.toHexString(System.identityHashCode(dialog.getShell())),
                                    inputRunnable, blocker,
                                    Integer.toHexString(System.identityHashCode(blocker)));

                            log.info(message);

                            /* Requeue the dialog */
                            final Job showProgressUIJob = createProgressUIJob(inputRunnable, wrappedRunnable,
                                    dialog);

                            showProgressUIJob.setSystem(true);
                            showProgressUIJob.schedule(deferTimeMillis);

                            return;
                        }
                    }

                    if (dialog.getShell() != null) {
                        if (log.isTraceEnabled()) {
                            final String messageFormat = "opening shell [{0} ({1})] for [{2}]"; //$NON-NLS-1$
                            final String message = MessageFormat.format(messageFormat, dialog.getShell(),
                                    Integer.toHexString(System.identityHashCode(dialog.getShell())),
                                    inputRunnable);

                            log.trace(message);
                        }
                    }

                    /*
                     * It is safe to call dialog.open() even when the
                     * command has finished executing.
                     */
                    dialog.open();

                    /*
                     * this line works around a problem with progress
                     * monitor dialog: updates to the task name are not
                     * always displayed if openOnRun is false and the
                     * updates are made before the dialog is opened
                     *
                     * the fix is to cache changes made to the task name
                     * (through the interface wrapper classes defined below)
                     * and re-set the task name to the same value at a same
                     * time (after the dialog has opened)
                     */
                    wrappedRunnable.getCustomProgressMonitor().updateTaskNameIfSet();
                }
            });
            return Status.OK_STATUS;
        }
    };
}

From source file:IdentityMap.java

/**
 * {@inheritDoc}// w  ww .  java2s .co  m
 * @see java.util.Map#containsKey(java.lang.Object)
 */
public boolean containsKey(final Object key) {
    int hash = System.identityHashCode(key);
    int index = hash % _capacity;
    if (index < 0) {
        index = -index;
    }

    Entry entry = _buckets[index];
    while (entry != null) {
        if (entry.getKey() == key) {
            return true;
        }
        entry = entry.getNext();
    }
    return false;
}

From source file:org.lilyproject.util.hbase.LocalHTable.java

public HTablePool getHTablePool(Configuration conf) {
    HTablePool pool;//from   w ww. j a  v  a2s .c  om
    synchronized (HTABLE_POOLS) {
        pool = HTABLE_POOLS.get(conf);
        if (pool == null) {
            pool = new HTablePool(conf, 20, new HTableFactory());
            HTABLE_POOLS.put(conf, pool);
            Log log = LogFactory.getLog(LocalHTable.class);
            if (log.isDebugEnabled()) {
                log.debug("Created a new HTablePool instance for conf " + System.identityHashCode(conf));
            }
        }
    }
    return pool;
}