org.perf4j.slf4j.Slf4JStopWatch Java Examples

The following examples show how to use org.perf4j.slf4j.Slf4JStopWatch. 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 check out the related API usage on the sidebar.
Example #1
Source File: CollectionDatasourceImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Load data from middleware into {@link #data} field.
 * <p>In case of error sets {@link #dataLoadError} field to the exception object.</p>
 * @param params    datasource parameters, as described in {@link CollectionDatasource#refresh(java.util.Map)}
 */
protected void loadData(Map<String, Object> params) {
    Security security = AppBeans.get(Security.NAME);
    if (!security.isEntityOpPermitted(metaClass, EntityOp.READ)) {
        return;
    }

    String tag = getLoggingTag("CDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    if (needLoading()) {
        LoadContext context = beforeLoadData(params);
        if (context == null) {
            return;
        }
        try {
            Collection<T> entities = dataSupplier.loadList(context);

            afterLoadData(params, context, entities);
        } catch (Throwable e) {
            dataLoadError = e;
        }
    }

    sw.stop();
}
 
Example #2
Source File: AbstractTreeDatasource.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("TDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    clear();

    this.tree = loadTree(params);

    Map<K, Node<T>> targetNodes = new HashMap<>();
    if (tree != null) {
        for (Node<T> node : tree.toList()) {
            final T entity = node.getData();
            final K id = entity.getId();

            data.put(id, entity);
            attachListener(entity);

            targetNodes.put(id, node);
        }
    }

    this.nodes = targetNodes;

    sw.stop();
}
 
Example #3
Source File: WebJarResourceResolver.java    From cuba with Apache License 2.0 6 votes vote down vote up
@EventListener
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 200)
protected void init(AppContextInitializedEvent event) {
    StopWatch stopWatch = new Slf4JStopWatch("WebJARs");
    try {
        ApplicationContext applicationContext = event.getApplicationContext();

        ClassLoader classLoader = applicationContext.getClassLoader();

        log.debug("Scanning WebJAR resources in {}", classLoader);

        scanResources(applicationContext);

        log.debug("Loaded {} WebJAR paths", mapping.size());
    } catch (IOException e) {
        throw new RuntimeException("Unable to load WebJAR resources", e);
    } finally {
        stopWatch.stop();
    }
}
 
Example #4
Source File: AbstractViewRepository.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected void init() {
    StopWatch initTiming = new Slf4JStopWatch("ViewRepository.init." + getClass().getSimpleName());

    storage.clear();
    readFileNames.clear();

    String configName = AppContext.getProperty("cuba.viewsConfig");
    if (!StringUtils.isBlank(configName)) {
        Element rootElem = DocumentHelper.createDocument().addElement("views");

        StringTokenizer tokenizer = new StringTokenizer(configName);
        for (String fileName : tokenizer.getTokenArray()) {
            addFile(rootElem, fileName);
        }

        viewLoader.checkDuplicates(rootElem);

        for (Element viewElem : Dom4j.elements(rootElem, "view")) {
            deployView(rootElem, viewElem, new HashSet<>());
        }
    }

    initTiming.stop();
}
 
Example #5
Source File: JavaClassLoader.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Class loadClass(final String fullClassName, boolean resolve) throws ClassNotFoundException {
    String containerClassName = StringUtils.substringBefore(fullClassName, "$");

    StopWatch loadingWatch = new Slf4JStopWatch("LoadClass");
    try {
        lock(containerClassName);
        Class clazz;

        //first check if there is a ".class" file in the "conf" directory
        File classFile = classFilesProvider.getClassFile(containerClassName);
        if (classFile.exists()) {
            return loadClassFromClassFile(fullClassName, containerClassName, classFile);
        }

        //then check if a ".java" source file is deployed to the "conf" directory
        if (sourceProvider.getSourceFile(containerClassName).exists()) {
            return loadClassFromJavaSources(fullClassName, containerClassName);
        }

        //default class loading
        clazz = super.loadClass(fullClassName, resolve);
        return clazz;
    } finally {
        unlock(containerClassName);
        loadingWatch.stop();
    }
}
 
Example #6
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public List<AppFolder> reloadAppFolders(List<AppFolder> folders) {
    log.debug("Reloading AppFolders {}", folders);

    StopWatch stopWatch = new Slf4JStopWatch("AppFolders");
    stopWatch.start();

    try {
        if (!folders.isEmpty()) {
            Binding binding = new Binding();
            binding.setVariable("persistence", persistence);
            binding.setVariable("metadata", metadata);
            binding.setProperty("userSession", userSessionSource.getUserSession());

            for (AppFolder folder : folders) {
                Transaction tx = persistence.createTransaction();
                try {
                    if (loadFolderQuantity(binding, folder)) {
                        tx.commit();
                    }
                } finally {
                    tx.end();
                }
            }
        }

        return folders;
    } finally {
        stopWatch.stop();
    }
}
 
Example #7
Source File: ValueCollectionDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #8
Source File: ValueGroupDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VGDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #9
Source File: ValueHierarchicalDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VHDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #10
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public List<SearchFolder> loadSearchFolders() {
    log.debug("Loading SearchFolders");

    StopWatch stopWatch = new Slf4JStopWatch("SearchFolders");
    stopWatch.start();

    Transaction tx = persistence.createTransaction();
    try {
        EntityManager em = persistence.getEntityManager();
        MetaClass effectiveMetaClass = metadata.getExtendedEntities().getEffectiveMetaClass(SearchFolder.class);
        TypedQuery<SearchFolder> q = em.createQuery("select f from "+ effectiveMetaClass.getName() +" f " +
                "left join f.user u on u.id = ?1 " +
                "where (u.id = ?1 or u is null) " +
                "order by f.sortOrder, f.name",
                SearchFolder.class);
        q.setViewName("searchFolders");
        q.setParameter(1, userSessionSource.currentOrSubstitutedUserId());
        List<SearchFolder> list = q.getResultList();
        tx.commit();
        return list;
    } finally {
        tx.end();

        stopWatch.stop();
    }
}
 
Example #11
Source File: DesktopTableCellEditor.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Component getCellComponent(int row) {
    Entity item = desktopAbstractTable.getTableModel().getItem(row);

    StopWatch sw = new Slf4JStopWatch("TableColumnGenerator." + desktopAbstractTable.getId());
    @SuppressWarnings("unchecked")
    com.haulmont.cuba.gui.components.Component component = columnGenerator.generateCell(item);
    sw.stop();

    Component comp;
    if (component == null) {
        comp = new JLabel("");
    } else if (component instanceof Table.PlainTextCell) {
        comp = new JLabel(((Table.PlainTextCell) component).getText());
    } else {
        if (component instanceof BelongToFrame) {
            BelongToFrame belongToFrame = (BelongToFrame) component;
            if (belongToFrame.getFrame() == null) {
                belongToFrame.setFrame(desktopAbstractTable.getFrame());
            }
        }
        component.setParent(desktopAbstractTable);

        JComponent jComposition = DesktopComponentsHelper.getComposition(component);
        jComposition.putClientProperty(CELL_EDITOR_TABLE, desktopAbstractTable.getComponent());
        jComposition.putClientProperty(CELL_COMPONENT, component);

        comp = jComposition;
    }

    cache.put(row, comp);
    return comp;
}
 
Example #12
Source File: Scheduling.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void processScheduledTasks(boolean onlyIfActive) {
    if (onlyIfActive && !isActive())
        return;

    log.debug("Processing scheduled tasks");
    if (schedulingStartTime == 0)
        schedulingStartTime = timeSource.currentTimeMillis();

    authentication.begin();
    try {
        StopWatch sw = new Slf4JStopWatch("Scheduling.processTasks");
        Coordinator.Context context;
        try {
            context = coordinator.begin();
        } catch (SchedulingLockException e) {
            return;
        }
        try {
            for (ScheduledTask task : context.getTasks()) {
                processTask(task);
            }
        } finally {
            coordinator.end(context);
        }
        sw.stop();
    } finally {
        authentication.end();
    }
}
 
Example #13
Source File: MessagesClientImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
protected String searchRemotely(String pack, String key, Locale locale) {
    if (!remoteSearch || !AppContext.isStarted())
        return null;

    if (log.isTraceEnabled())
        log.trace("searchRemotely: " + pack + "/" +  LocaleResolver.localeToString(locale) + "/" + key);

    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchRemotely");
    try {
        String message = localizedMessageService.getMessage(pack, key, locale);
        if (key.equals(message))
            return null;
        else
            return message;
    } catch (Exception e) {
        List list = ExceptionUtils.getThrowableList(e);
        for (Object throwable : list) {
            if (throwable instanceof SocketException) {
                log.trace("searchRemotely: {}", throwable);
                return null; // silently ignore network errors
            }
        }
        throw (RuntimeException) e;
    } finally {
        stopWatch.stop();
    }
}
 
Example #14
Source File: AbstractMessages.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String searchClasspath(String pack, String key, Locale locale, Locale truncatedLocale, Set<String> passedPacks) {
    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchClasspath");
    try {
        String cacheKey = makeCacheKey(pack, key, locale, truncatedLocale);

        String msg = strCache.get(cacheKey);
        if (msg != null)
            return msg;

        log.trace("searchClasspath: {}", cacheKey);

        String packPath = "/" + pack.replaceAll("\\.", "/");
        while (packPath != null) {
            Properties properties = loadPropertiesFromResource(packPath, locale, truncatedLocale);
            if (properties != PROPERTIES_NOT_FOUND) {
                msg = getMessageFromProperties(pack, key, locale, truncatedLocale, properties, passedPacks);
                if (msg != null)
                    return msg;
            }
            // not found, keep searching
            int pos = packPath.lastIndexOf("/");
            if (pos < 0)
                packPath = null;
            else
                packPath = packPath.substring(0, pos);
        }
        return null;
    } finally {
        stopWatch.stop();
    }
}
 
Example #15
Source File: AbstractMessages.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String searchFiles(String pack, String key, Locale locale, Locale truncatedLocale, Set<String> passedPacks) {
    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchFiles");
    try {
        String cacheKey = makeCacheKey(pack, key, locale, truncatedLocale);

        String msg = strCache.get(cacheKey);
        if (msg != null)
            return msg;

        log.trace("searchFiles: {}", cacheKey);

        String packPath = confDir + "/" + pack.replaceAll("\\.", "/");
        while (packPath != null && !packPath.equals(confDir)) {
            Properties properties = loadPropertiesFromFile(packPath, locale, truncatedLocale);
            if (properties != PROPERTIES_NOT_FOUND) {
                msg = getMessageFromProperties(pack, key, locale, truncatedLocale, properties, passedPacks);
                if (msg != null)
                    return msg;
            }
            // not found, keep searching
            int pos = packPath.lastIndexOf("/");
            if (pos < 0)
                packPath = null;
            else
                packPath = packPath.substring(0, pos);
        }
        return null;
    } finally {
        stopWatch.stop();
    }
}
 
Example #16
Source File: AbstractViewRepository.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void replaceOverridden(View replacementView) {
    StopWatch replaceTiming = new Slf4JStopWatch("ViewRepository.replaceOverridden");

    HashSet<View> checked = new HashSet<>();

    for (View view : getAllInitialized()) {
        if (!checked.contains(view)) {
            replaceOverridden(view, replacementView, checked);
        }
    }

    replaceTiming.stop();
}
 
Example #17
Source File: JmxInstancesDatasource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("CDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    detachListener(data.values());
    data.clear();

    for (JmxInstance jmxInstance : jmxControlAPI.getInstances()) {
        data.put(jmxInstance.getId(), jmxInstance);
        attachListener(jmxInstance);
    }

    sw.stop();
}
 
Example #18
Source File: ClusterManager.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void receive(Message msg) {
    byte[] bytes = msg.getBuffer();
    if (bytes == null) {
        log.debug("Null buffer received");
        return;
    }
    StopWatch sw = new Slf4JStopWatch();
    String simpleClassName = null;
    try {
        Serializable data;
        try {
            data = (Serializable) SerializationSupport.deserialize(bytes);
        } catch (Exception e) {
            log.error("Cluster message deserialization error", e);
            throw new RuntimeException("Cluster message deserialization error", e);
        }
        String className = data.getClass().getName();
        simpleClassName = data.getClass().getSimpleName();
        log.debug("Received message: {}: {} ({} bytes)", data.getClass(), data, bytes.length);
        MessageStat stat = messagesStat.get(className);
        if (stat != null) {
            stat.updateReceived(bytes.length);
        }
        @SuppressWarnings("unchecked")
        ClusterListener<Serializable> listener = listeners.get(className);
        if (listener != null) {
            listener.receive(data);
        }
    } finally {
        sw.stop(String.format("receiveClusterMessage(%s)", simpleClassName));
    }
}
 
Example #19
Source File: ClusterManager.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setState(InputStream input) {
    log.debug("Receiving state");

    try (DataInputStream in = new DataInputStream(input)) {
        if (input.available() == 0)
            return;

        String magic = in.readUTF();
        if (!STATE_MAGIC.equals(magic)) {
            log.debug("Invalid magic in state received");
            return;
        }
        int count = in.readInt();
        for (int i = 0; i < count; i++) {
            String name = in.readUTF();
            int len = in.readInt();
            StopWatch sw = new Slf4JStopWatch(String.format("setClusterState(%s)", name));
            try {
                log.debug("Receiving state: {} ({} bytes)", name, len);
                byte[] data = new byte[len];
                int c = in.read(data);
                if (c != len) {
                    log.error("Error receiving state: invalid data length");
                    return;
                }
                ClusterListener listener = listeners.get(name);
                if (listener != null) {
                    listener.setState(data);
                }
            } finally {
                sw.stop();
            }
        }
        log.debug("State received");
    } catch (Exception e) {
        log.error("Error receiving state", e);
    }
}
 
Example #20
Source File: EmailSender.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void sendEmail(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = createMimeMessage(sendingMessage);

    StopWatch sw = new Slf4JStopWatch("EmailSender.send");
    mailSender.send(msg);
    sw.stop();

    log.info("Email '{}' to '{}' has been sent successfully", msg.getSubject(), sendingMessage.getAddress());
}
 
Example #21
Source File: PerformanceLogInterceptor.java    From cuba with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"UnusedDeclaration", "UnnecessaryLocalVariable"})
protected Object aroundInvoke(ProceedingJoinPoint ctx) throws Throwable {
    StopWatch stopWatch = new Slf4JStopWatch(ctx.getSignature().toShortString());
    try {
        stopWatch.start();
        Object res = ctx.proceed();
        return res;
    } finally {
        stopWatch.stop();
    }
}
 
Example #22
Source File: UIPerformanceLogger.java    From cuba with Apache License 2.0 4 votes vote down vote up
public static StopWatch createStopWatch(ScreenLifeCycle lifeCycle, String loggingId) {
    return new Slf4JStopWatch(loggingId + lifeCycle.getSuffix(), LoggerFactory.getLogger(UIPerformanceLogger.class));
}
 
Example #23
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public List<AppFolder> loadAppFolders() {
    log.debug("Loading AppFolders");

    StopWatch stopWatch = new Slf4JStopWatch("AppFolders");
    stopWatch.start();

    List<AppFolder> resultList;
    try (Transaction tx = persistence.createTransaction()) {
        String metaClassName = metadata.getExtendedEntities().getEffectiveMetaClass(AppFolder.class).getName();
        TypedQuery<AppFolder> q = persistence.getEntityManager().createQuery(
                "select f from " + metaClassName + " f order by f.sortOrder, f.name", AppFolder.class);

        resultList = q.getResultList();
        // fetch parent folder
        resultList.forEach(Folder::getParent);

        tx.commit();
    } finally {
        stopWatch.stop();
    }

    if (CollectionUtils.isNotEmpty(resultList)) {
        Binding binding = new Binding();
        binding.setVariable("persistence", persistence);
        binding.setVariable("metadata", metadata);
        binding.setVariable("userSession", userSessionSource.getUserSession());

        Iterator<AppFolder> iterator = resultList.iterator();
        while (iterator.hasNext()) {
            AppFolder folder = iterator.next();
            try (Transaction tx = persistence.createTransaction()) {
                boolean evaluatedVisibilityScript = true;
                try {
                    if (!StringUtils.isBlank(folder.getVisibilityScript())) {
                        binding.setVariable("folder", folder);
                        Boolean visible = runScript(folder.getVisibilityScript(), binding);
                        if (BooleanUtils.isFalse(visible)) {
                            iterator.remove();
                            continue;
                        }
                    }
                } catch (Exception e) {
                    log.warn("Unable to evaluate AppFolder visibility script for folder: id: {}  name: {}",
                            folder.getId(), folder.getName(), e);
                    // because EclipseLink Query marks transaction as rollback-only on JPQL syntax errors
                    evaluatedVisibilityScript = false;
                }

                boolean evaluatedQuantityScript = loadFolderQuantity(binding, folder);

                if (evaluatedVisibilityScript && evaluatedQuantityScript) {
                    tx.commit();
                }
            }
        }
    }

    return resultList;
}
 
Example #24
Source File: MenuItemCommands.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected StopWatch createStopWatch(MenuItem item) {
    return new Slf4JStopWatch("MenuItem." + item.getId(), LoggerFactory.getLogger(UIPerformanceLogger.class));
}
 
Example #25
Source File: Perform.java    From ns4_frame with Apache License 2.0 4 votes vote down vote up
public void performMethod() throws Exception{
    StopWatch stopWatch = new Slf4JStopWatch(LogUtils.getFullyMethodName());
    TimeUnit.MILLISECONDS.sleep(100);
    stopWatch.stop();
}
 
Example #26
Source File: DesktopAbstractTable.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the height of each row into the preferred height of the tallest cell in that row.
 */
public void packRows() {
    if (!contentRepaintEnabled) {
        return;
    }

    impl.setRowHeight(defaultRowHeight);

    for (Column column : columnsOrder) {
        if (column.isEditable()) {
            impl.setRowHeight(defaultEditableRowHeight);
            break;
        }
    }

    if (allColumnsAreInline()) {
        return;
    }

    int preferredRowHeight = -1;
    boolean equalsRowHeight = true;

    StopWatch sw = new Slf4JStopWatch("DAT packRows " + id);
    for (int r = 0; r < impl.getRowCount(); r++) {
        int h = getPreferredRowHeight(r);

        if (preferredRowHeight == -1) {
            preferredRowHeight = h;
        } else if (preferredRowHeight != h) {
            equalsRowHeight = false;
        }

        if (impl.getRowHeight(r) != h) {
            impl.setRowHeight(r, h);
        }
    }

    if (equalsRowHeight && preferredRowHeight > 0) {
        impl.setRowHeight(preferredRowHeight);
    }

    sw.stop();
}
 
Example #27
Source File: ManagedBeanInfoDatasource.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
protected Tree<ManagedBeanInfo> loadTree(Map<String, Object> params) {
    String tag = getLoggingTag("TDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));
    List<Node<ManagedBeanInfo>> nodes = new ArrayList<>();

    if (jmxInstance != null) {
        List<ManagedBeanDomain> domains = jmxControlAPI.getDomains(jmxInstance);

        Map<String, Node<ManagedBeanInfo>> domainMap = new HashMap<>();

        for (ManagedBeanDomain mbd : domains) {
            ManagedBeanInfo dummy = metadata.create(ManagedBeanInfo.class);
            dummy.setDomain(mbd.getName());

            Node<ManagedBeanInfo> node = new Node<>(dummy);
            domainMap.put(mbd.getName(), node);
            nodes.add(node);
        }

        List<ManagedBeanInfo> list = loadManagedBeans(params);
        for (ManagedBeanInfo mbi : list) {
            if (mbi != null) {
                if (domainMap.containsKey(mbi.getDomain())) {
                    domainMap.get(mbi.getDomain()).addChild(new Node<>(mbi));
                }
            }
        }

        // remove root nodes that might have left without children after filtering
        for (Node<ManagedBeanInfo> rootNode : new ArrayList<>(nodes)) {
            if (rootNode.getChildren().isEmpty()) {
                nodes.remove(rootNode);
            }
        }
    }

    sw.stop();

    return new Tree<>(nodes);
}
 
Example #28
Source File: SegmentIDGenImpl.java    From Leaf with Apache License 2.0 4 votes vote down vote up
public void updateSegmentFromDb(String key, Segment segment) {
    StopWatch sw = new Slf4JStopWatch();
    SegmentBuffer buffer = segment.getBuffer();
    LeafAlloc leafAlloc;
    if (!buffer.isInitOk()) {
        leafAlloc = dao.updateMaxIdAndGetLeafAlloc(key);
        buffer.setStep(leafAlloc.getStep());
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc中的step为DB中的step
    } else if (buffer.getUpdateTimestamp() == 0) {
        leafAlloc = dao.updateMaxIdAndGetLeafAlloc(key);
        buffer.setUpdateTimestamp(System.currentTimeMillis());
        buffer.setStep(leafAlloc.getStep());
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc中的step为DB中的step
    } else {
        long duration = System.currentTimeMillis() - buffer.getUpdateTimestamp();
        int nextStep = buffer.getStep();
        if (duration < SEGMENT_DURATION) {
            if (nextStep * 2 > MAX_STEP) {
                //do nothing
            } else {
                nextStep = nextStep * 2;
            }
        } else if (duration < SEGMENT_DURATION * 2) {
            //do nothing with nextStep
        } else {
            nextStep = nextStep / 2 >= buffer.getMinStep() ? nextStep / 2 : nextStep;
        }
        logger.info("leafKey[{}], step[{}], duration[{}mins], nextStep[{}]", key, buffer.getStep(), String.format("%.2f",((double)duration / (1000 * 60))), nextStep);
        LeafAlloc temp = new LeafAlloc();
        temp.setKey(key);
        temp.setStep(nextStep);
        leafAlloc = dao.updateMaxIdByCustomStepAndGetLeafAlloc(temp);
        buffer.setUpdateTimestamp(System.currentTimeMillis());
        buffer.setStep(nextStep);
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc的step为DB中的step
    }
    // must set value before set max
    long value = leafAlloc.getMaxId() - buffer.getStep();
    segment.getValue().set(value);
    segment.setMax(leafAlloc.getMaxId());
    segment.setStep(buffer.getStep());
    sw.stop("updateSegmentFromDb", key + " " + segment);
}
 
Example #29
Source File: SegmentIDGenImpl.java    From SpringMVC-Project with MIT License 4 votes vote down vote up
public void updateSegmentFromDb(String key, Segment segment) {
    StopWatch sw = new Slf4JStopWatch();
    SegmentBuffer buffer = segment.getBuffer();
    LeafAlloc leafAlloc;
    if (!buffer.isInitOk()) {
        leafAlloc = dao.updateMaxIdAndGetLeafAlloc(key);
        buffer.setStep(leafAlloc.getStep());
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc中的step为DB中的step
    } else if (buffer.getUpdateTimestamp() == 0) {
        leafAlloc = dao.updateMaxIdAndGetLeafAlloc(key);
        buffer.setUpdateTimestamp(System.currentTimeMillis());
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc中的step为DB中的step
    } else {
        long duration = System.currentTimeMillis() - buffer.getUpdateTimestamp();
        int nextStep = buffer.getStep();
        if (duration < SEGMENT_DURATION) {
            if (nextStep * 2 > MAX_STEP) {
                //do nothing
            } else {
                nextStep = nextStep * 2;
            }
        } else if (duration < SEGMENT_DURATION * 2) {
            //do nothing with nextStep
        } else {
            nextStep = nextStep / 2 >= buffer.getMinStep() ? nextStep / 2 : nextStep;
        }
        logger.info("leafKey[{}], step[{}], duration[{}mins], nextStep[{}]", key, buffer.getStep(), String.format("%.2f", ((double) duration / (1000 * 60))), nextStep);
        LeafAlloc temp = new LeafAlloc();
        temp.setKey(key);
        temp.setStep(nextStep);
        leafAlloc = dao.updateMaxIdByCustomStepAndGetLeafAlloc(temp);
        buffer.setUpdateTimestamp(System.currentTimeMillis());
        buffer.setStep(nextStep);
        buffer.setMinStep(leafAlloc.getStep());//leafAlloc的step为DB中的step
    }
    // must set value before set max
    long value = leafAlloc.getMaxId() - buffer.getStep();
    segment.getValue().set(value);
    segment.setMax(leafAlloc.getMaxId());
    segment.setStep(buffer.getStep());
    sw.stop("updateSegmentFromDb", key + " " + segment);
}
 
Example #30
Source File: Perform.java    From ns4_frame with Apache License 2.0 4 votes vote down vote up
public void performMethodOnce() throws Exception{
    StopWatch stopWatch = new Slf4JStopWatch(LogUtils.getFullyMethodName());
    TimeUnit.MILLISECONDS.sleep(200);
    stopWatch.stop();
}