Example usage for java.util.concurrent TimeUnit MICROSECONDS

List of usage examples for java.util.concurrent TimeUnit MICROSECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MICROSECONDS.

Prototype

TimeUnit MICROSECONDS

To view the source code for java.util.concurrent TimeUnit MICROSECONDS.

Click Source Link

Document

Time unit representing one thousandth of a millisecond.

Usage

From source file:com.netflix.dyno.jedis.DynoJedisPipeline.java

/**
 * This method is a BinaryRedisPipeline command which dyno does not yet properly
 * support, therefore the interface is not yet implemented since only a few
 * binary commands are present./*  w  w  w  . j  a v a 2 s  .  c  o  m*/
 */
public Response<String> hmset(final byte[] key, final Map<byte[], byte[]> hash) {
    if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) {
        return new PipelineOperation<String>() {
            @Override
            Response<String> execute(Pipeline jedisPipeline) throws DynoException {
                long startTime = System.nanoTime() / 1000;
                try {
                    return jedisPipeline.hmset(key, hash);
                } finally {
                    long duration = System.nanoTime() / 1000 - startTime;
                    opMonitor.recordSendLatency(OpName.HMSET.name(), duration, TimeUnit.MICROSECONDS);
                }
            }
        }.execute(key, OpName.HMSET);
    } else {
        return new PipelineCompressionOperation<String>() {
            @Override
            Response<String> execute(final Pipeline jedisPipeline) throws DynoException {
                return new PipelineResponse(null).apply(new Func0<Response<String>>() {
                    @Override
                    public Response<String> call() {
                        return jedisPipeline.hmset(key, CollectionUtils.transform(hash,
                                new CollectionUtils.MapEntryTransform<byte[], byte[], byte[]>() {
                                    @Override
                                    public byte[] get(byte[] key, byte[] val) {
                                        return compressValue(val);
                                    }
                                }));
                    }
                });
            }
        }.execute(key, OpName.HMSET);
    }
}

From source file:com.twitter.distributedlog.lock.ZKSessionLock.java

synchronized LockWaiter waitForTry(Stopwatch stopwatch, Future<LockWaiter> tryFuture) throws LockingException {
    boolean success = false;
    boolean stateChanged = false;
    LockWaiter waiter;/*from  ww w  .  j  a  va 2 s. c o  m*/
    try {
        waiter = Await.result(tryFuture, Duration.fromMilliseconds(lockOpTimeout));
        success = true;
    } catch (LockStateChangedException ex) {
        stateChanged = true;
        throw ex;
    } catch (LockingException ex) {
        throw ex;
    } catch (TimeoutException toe) {
        tryTimeouts.inc();
        throw new LockingException(lockPath, "Timeout during try phase of lock acquire", toe);
    } catch (Exception ex) {
        String message = getLockId() + " failed to lock " + lockPath;
        throw new LockingException(lockPath, message, ex);
    } finally {
        if (success) {
            tryStats.registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
        } else {
            tryStats.registerFailedEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS));
        }
        // This can only happen for a Throwable thats not an
        // Exception, i.e. an Error
        if (!success && !stateChanged) {
            unlock();
        }
    }
    return waiter;
}

From source file:com.twitter.distributedlog.BKLogHandler.java

protected List<LogSegmentMetadata> getLedgerList(boolean forceFetch, boolean fetchFullList,
        Comparator<LogSegmentMetadata> comparator, boolean throwOnEmpty) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    boolean success = false;
    try {//from  w ww . j av  a 2s .  c om
        List<LogSegmentMetadata> segments = doGetLedgerList(forceFetch, fetchFullList, comparator,
                throwOnEmpty);
        success = true;
        return segments;
    } finally {
        OpStatsLogger statsLogger = fetchFullList ? getFullListStat : getFilteredListStat;
        if (success) {
            statsLogger.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        } else {
            statsLogger.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
    }
}

From source file:org.apache.nifi.avro.AvroTypeUtil.java

/**
 * Convert an Avro object to a normal Java objects for further processing.
 * The counter-part method which convert a raw value to an Avro object is {@link #convertToAvroObject(Object, Schema, String, Charset)}
 *//*from  www.ja va 2 s  .  com*/
private static Object normalizeValue(final Object value, final Schema avroSchema, final String fieldName) {
    if (value == null) {
        return null;
    }

    switch (avroSchema.getType()) {
    case INT: {
        final LogicalType logicalType = avroSchema.getLogicalType();
        if (logicalType == null) {
            return value;
        }

        final String logicalName = logicalType.getName();
        if (LOGICAL_TYPE_DATE.equals(logicalName)) {
            // date logical name means that the value is number of days since Jan 1, 1970
            return new java.sql.Date(TimeUnit.DAYS.toMillis((int) value));
        } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalName)) {
            // time-millis logical name means that the value is number of milliseconds since midnight.
            return new java.sql.Time((int) value);
        }

        break;
    }
    case LONG: {
        final LogicalType logicalType = avroSchema.getLogicalType();
        if (logicalType == null) {
            return value;
        }

        final String logicalName = logicalType.getName();
        if (LOGICAL_TYPE_TIME_MICROS.equals(logicalName)) {
            return new java.sql.Time(TimeUnit.MICROSECONDS.toMillis((long) value));
        } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalName)) {
            return new java.sql.Timestamp((long) value);
        } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalName)) {
            return new java.sql.Timestamp(TimeUnit.MICROSECONDS.toMillis((long) value));
        }
        break;
    }
    case UNION:
        if (value instanceof GenericData.Record) {
            final GenericData.Record avroRecord = (GenericData.Record) value;
            return normalizeValue(value, avroRecord.getSchema(), fieldName);
        }
        return convertUnionFieldValue(value, avroSchema, schema -> normalizeValue(value, schema, fieldName),
                fieldName);
    case RECORD:
        final GenericData.Record record = (GenericData.Record) value;
        final Schema recordSchema = record.getSchema();
        final List<Field> recordFields = recordSchema.getFields();
        final Map<String, Object> values = new HashMap<>(recordFields.size());
        for (final Field field : recordFields) {
            final Object avroFieldValue = record.get(field.name());
            final Object fieldValue = normalizeValue(avroFieldValue, field.schema(),
                    fieldName + "/" + field.name());
            values.put(field.name(), fieldValue);
        }
        final RecordSchema childSchema = AvroTypeUtil.createSchema(recordSchema, false);
        return new MapRecord(childSchema, values);
    case BYTES:
        final ByteBuffer bb = (ByteBuffer) value;
        final LogicalType logicalType = avroSchema.getLogicalType();
        if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) {
            return new Conversions.DecimalConversion().fromBytes(bb, avroSchema, logicalType);
        }
        return AvroTypeUtil.convertByteArray(bb.array());
    case FIXED:
        final GenericFixed fixed = (GenericFixed) value;
        return AvroTypeUtil.convertByteArray(fixed.bytes());
    case ENUM:
        return value.toString();
    case NULL:
        return null;
    case STRING:
        return value.toString();
    case ARRAY:
        if (value instanceof List) {
            final List<?> list = (List<?>) value;
            final Object[] valueArray = new Object[list.size()];
            for (int i = 0; i < list.size(); i++) {
                final Schema elementSchema = avroSchema.getElementType();
                valueArray[i] = normalizeValue(list.get(i), elementSchema, fieldName + "[" + i + "]");
            }
            return valueArray;
        } else {
            final GenericData.Array<?> array = (GenericData.Array<?>) value;
            final Object[] valueArray = new Object[array.size()];
            for (int i = 0; i < array.size(); i++) {
                final Schema elementSchema = avroSchema.getElementType();
                valueArray[i] = normalizeValue(array.get(i), elementSchema, fieldName + "[" + i + "]");
            }
            return valueArray;
        }
    case MAP:
        final Map<?, ?> avroMap = (Map<?, ?>) value;
        final Map<String, Object> map = new HashMap<>(avroMap.size());
        for (final Map.Entry<?, ?> entry : avroMap.entrySet()) {
            Object obj = entry.getValue();
            if (obj instanceof Utf8 || obj instanceof CharSequence) {
                obj = obj.toString();
            }

            final String key = entry.getKey().toString();
            obj = normalizeValue(obj, avroSchema.getValueType(), fieldName + "[" + key + "]");

            map.put(key, obj);
        }

        return map;
    }

    return value;
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

synchronized LockWaiter waitForTry(Stopwatch stopwatch, CompletableFuture<LockWaiter> tryFuture)
        throws LockingException {
    boolean success = false;
    boolean stateChanged = false;
    LockWaiter waiter;/* ww  w .  j a va 2s .c o  m*/
    try {
        waiter = FutureUtils.result(tryFuture, lockOpTimeout, TimeUnit.MILLISECONDS);
        success = true;
    } catch (LockStateChangedException ex) {
        stateChanged = true;
        throw ex;
    } catch (LockingException ex) {
        throw ex;
    } catch (TimeoutException toe) {
        tryTimeouts.inc();
        throw new LockingException(lockPath, "Timeout during try phase of lock acquire", toe);
    } catch (Exception ex) {
        String message = getLockId() + " failed to lock " + lockPath;
        throw new LockingException(lockPath, message, ex);
    } finally {
        if (success) {
            tryStats.registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
        } else {
            tryStats.registerFailedEvent(stopwatch.elapsed(TimeUnit.MICROSECONDS), TimeUnit.MICROSECONDS);
        }
        // This can only happen for a Throwable thats not an
        // Exception, i.e. an Error
        if (!success && !stateChanged) {
            unlock();
        }
    }
    return waiter;
}

From source file:com.netflix.dyno.jedis.DynoJedisPipeline.java

@Override
public Response<String> hmset(final String key, final Map<String, String> hash) {
    if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) {
        return new PipelineOperation<String>() {
            @Override//  w w  w  .ja  v  a 2 s  . c o  m
            Response<String> execute(Pipeline jedisPipeline) throws DynoException {
                long startTime = System.nanoTime() / 1000;
                try {
                    return jedisPipeline.hmset(key, hash);
                } finally {
                    long duration = System.nanoTime() / 1000 - startTime;
                    opMonitor.recordSendLatency(OpName.HMSET.name(), duration, TimeUnit.MICROSECONDS);
                }
            }
        }.execute(key, OpName.HMSET);
    } else {
        return new PipelineCompressionOperation<String>() {
            @Override
            Response<String> execute(final Pipeline jedisPipeline) throws DynoException {
                return new PipelineResponse(null).apply(new Func0<Response<String>>() {
                    @Override
                    public Response<String> call() {
                        return jedisPipeline.hmset(key, CollectionUtils.transform(hash,
                                new CollectionUtils.MapEntryTransform<String, String, String>() {
                                    @Override
                                    public String get(String key, String val) {
                                        return compressValue(val);
                                    }
                                }));
                    }
                });
            }
        }.execute(key, OpName.HMSET);
    }

}

From source file:net.centro.rtb.monitoringcenter.MonitoringCenter.java

private static void initGraphiteReporter(final GraphiteReporterConfig graphiteReporterConfig) {
    HostAndPort hostAndPort = graphiteReporterConfig.getAddress();
    InetSocketAddress inetSocketAddress = new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());

    GraphiteSender graphiteSender = graphiteReporterConfig.getEnableBatching()
            ? new PickledGraphite(inetSocketAddress)
            : new Graphite(inetSocketAddress);

    graphiteReporter = GraphiteReporter.forRegistry(metricRegistry).prefixedWith(prefix)
            .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MICROSECONDS)
            .filter(new MetricFilter() {
                @Override//from   www  . j a  va  2  s .  c  o  m
                public boolean matches(String name, Metric metric) {
                    boolean passedWhitelist = false;
                    if (graphiteReporterConfig.getStartsWithFilters().isEmpty()) {
                        passedWhitelist = true;
                    } else {
                        passedWhitelist = matchesStartsWithFilters(name,
                                graphiteReporterConfig.getStartsWithFilters().toArray(new String[] {}));
                    }

                    if (!passedWhitelist) {
                        return false;
                    }

                    if (graphiteReporterConfig.getBlockedStartsWithFilters().isEmpty()) {
                        return true;
                    } else {
                        return !matchesStartsWithFilters(name,
                                graphiteReporterConfig.getBlockedStartsWithFilters().toArray(new String[] {}));
                    }
                }
            }).build(graphiteSender);

    graphiteReporter.start(graphiteReporterConfig.getReportingIntervalInSeconds(), TimeUnit.SECONDS);
}

From source file:com.twitter.distributedlog.BKLogHandler.java

/**
 * Get a list of all segments in the journal.
 *///from w  w w .  j  a  va  2s. co m
protected List<LogSegmentMetadata> forceGetLedgerList(final Comparator<LogSegmentMetadata> comparator,
        final LogSegmentFilter segmentFilter, boolean throwOnEmpty) throws IOException {
    final List<LogSegmentMetadata> ledgers = new ArrayList<LogSegmentMetadata>();
    final AtomicInteger result = new AtomicInteger(-1);
    final CountDownLatch latch = new CountDownLatch(1);
    Stopwatch stopwatch = Stopwatch.createStarted();
    asyncGetLedgerListInternal(comparator, segmentFilter, null,
            new GenericCallback<List<LogSegmentMetadata>>() {
                @Override
                public void operationComplete(int rc, List<LogSegmentMetadata> logSegmentMetadatas) {
                    result.set(rc);
                    if (KeeperException.Code.OK.intValue() == rc) {
                        ledgers.addAll(logSegmentMetadatas);
                    } else {
                        LOG.error("Failed to get ledger list for {} : with error {}", getFullyQualifiedName(),
                                rc);
                    }
                    latch.countDown();
                }
            }, new AtomicInteger(conf.getZKNumRetries()), new AtomicLong(conf.getZKRetryBackoffStartMillis()));
    try {
        latch.await();
    } catch (InterruptedException e) {
        forceGetListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        throw new DLInterruptedException(
                "Interrupted on reading ledger list from zkfor " + getFullyQualifiedName(), e);
    }
    long elapsedMicros = stopwatch.stop().elapsed(TimeUnit.MICROSECONDS);

    KeeperException.Code rc = KeeperException.Code.get(result.get());
    if (rc == KeeperException.Code.OK) {
        forceGetListStat.registerSuccessfulEvent(elapsedMicros);
    } else {
        forceGetListStat.registerFailedEvent(elapsedMicros);
        if (KeeperException.Code.NONODE == rc) {
            throw new LogNotFoundException("Log " + getFullyQualifiedName() + " is not found");
        } else {
            throw new IOException("ZK Exception " + rc + " reading ledger list for " + getFullyQualifiedName());
        }
    }

    if (throwOnEmpty && ledgers.isEmpty()) {
        throw new LogEmptyException("Log " + getFullyQualifiedName() + " is empty");
    }
    return ledgers;
}

From source file:com.twitter.distributedlog.BKLogHandler.java

protected Future<List<LogSegmentMetadata>> asyncGetLedgerList(final boolean forceFetch,
        final boolean fetchFullList, final Comparator<LogSegmentMetadata> comparator,
        final boolean throwOnEmpty) {
    final Promise<List<LogSegmentMetadata>> promise = new Promise<List<LogSegmentMetadata>>();
    final Stopwatch stopwatch = Stopwatch.createStarted();
    final OpStatsLogger statsLogger = fetchFullList ? getFullListStat : getFilteredListStat;
    asyncDoGetLedgerList(forceFetch, fetchFullList, comparator, throwOnEmpty)
            .addEventListener(new FutureEventListener<List<LogSegmentMetadata>>() {
                @Override//  w  ww . jav a  2  s.  c o  m
                public void onSuccess(List<LogSegmentMetadata> value) {
                    statsLogger.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
                    promise.setValue(value);
                }

                @Override
                public void onFailure(Throwable cause) {
                    statsLogger.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
                    promise.setException(cause);
                }
            });
    return promise;
}

From source file:com.twitter.distributedlog.BKLogHandler.java

protected Future<List<LogSegmentMetadata>> asyncForceGetLedgerList(
        final Comparator<LogSegmentMetadata> comparator, final LogSegmentFilter segmentFilter,
        final boolean throwOnEmpty) {
    final Promise<List<LogSegmentMetadata>> promise = new Promise<List<LogSegmentMetadata>>();
    final Stopwatch stopwatch = Stopwatch.createStarted();
    asyncGetLedgerListWithRetries(comparator, segmentFilter, null)
            .addEventListener(new FutureEventListener<List<LogSegmentMetadata>>() {

                @Override//from  www . j  a  va2s.  c o  m
                public void onSuccess(List<LogSegmentMetadata> ledgers) {
                    forceGetListStat.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
                    if (ledgers.isEmpty() && throwOnEmpty) {
                        promise.setException(
                                new LogEmptyException("Log " + getFullyQualifiedName() + " is empty"));
                    } else {
                        promise.setValue(ledgers);
                    }
                }

                @Override
                public void onFailure(Throwable cause) {
                    forceGetListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
                    promise.setException(cause);
                }
            });
    return promise;
}