首页 \ 问答 \ CompletableFuture,包含已用时间信息(CompletableFuture with elapsed time information)

CompletableFuture,包含已用时间信息(CompletableFuture with elapsed time information)

我需要访问有关异步方法执行时间的信息。 所以,我正在尝试扩展CompletableFuture功能。 这是我使用装饰器模式用法的实现:

import java.util.concurrent.*;
import java.util.function.*;
import static lombok.AccessLevel.PRIVATE;
import lombok.AllArgsConstructor;
import lombok.experimental.Delegate;

@AllArgsConstructor(access = PRIVATE)
public class ContinuousCompletableFuture<T> extends CompletableFuture<T> {

    @Delegate
    private final CompletableFuture<T> baseFuture;

    private final long creationTime;

    public static <U> ContinuousCompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return new ContinuousCompletableFuture<>(CompletableFuture.supplyAsync(supplier));
    }

    private ContinuousCompletableFuture(CompletableFuture<T> baseFuture) {
        this.baseFuture = baseFuture;
        this.creationTime = System.nanoTime();
    }

    public Long getElapsedTime() {
        return (System.nanoTime() - creationTime) / 1000_000L;
    }

    public ContinuousCompletableFuture<Void> thenAcceptAsync(BiConsumer<? super T, Long> action) {
        CompletionStage<Long> elapsedTime = CompletableFuture.completedFuture(getElapsedTime());
        return new ContinuousCompletableFuture<>(baseFuture.thenAcceptBothAsync(elapsedTime, action), creationTime);
    }
}

第一次测试shouldReturnElapsedTime用提取的ContinuousCompletableFuture变量工作正常,但其他的shouldOperateWithOwnExecutionTime失败。 同时,我更喜欢在未来的代码中看到它既没有提取ContinuousCompletableFuture变量。

import java.util.concurrent.atomic.AtomicLong;
import lombok.extern.slf4j.Slf4j;
import org.junit.*;
import static org.junit.Assert.*;

@Slf4j
public class ContinuousCompletableFutureTest {

    private static final int DELAY = 1000;

    AtomicLong flag = new AtomicLong();

    ContinuousCompletableFuture<String> future;

    @Before
    public void before() {
        future = ContinuousCompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(DELAY);
            } catch (InterruptedException ex) {
                log.error("Error during ContinuousCompletableFuture execution", ex);
            }
            return "successfully completed";
        });
    }

    @Test
    public void shouldReturnElapsedTime() {
        future.thenAcceptAsync(s -> {
            long t = future.getElapsedTime();
            log.info("Elapsed {} ms to receive message \"{}\"", t, s);
            flag.set(t);
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            log.error("Error awaiting Test completion", ex);
        }

        assertTrue("Future completion should be delayed", flag.get() &t;= 0.75 * DELAY);
    }

    @Test
    public void shouldOperateWithOwnExecutionTime() {
        future.thenAcceptAsync((s, t) -> {
            log.info("Elapsed {} ms to receive message \"{}\"", t, s);
            flag.set(t);
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            log.error("Error awaiting Test completion", ex);
        }

        assertTrue("Future completion should be delayed", flag.get() >= 0.75 * DELAY);
    }
}

我假设我的问题在于错误thenAcceptBothAsync方法的用法。

有什么建议?


I need to have access to information about asynchronouos method execution time. So, I'm trying to extend CompletableFuture functionality. Here is my implementation with decorator pattern usage:

import java.util.concurrent.*;
import java.util.function.*;
import static lombok.AccessLevel.PRIVATE;
import lombok.AllArgsConstructor;
import lombok.experimental.Delegate;

@AllArgsConstructor(access = PRIVATE)
public class ContinuousCompletableFuture<T> extends CompletableFuture<T> {

    @Delegate
    private final CompletableFuture<T> baseFuture;

    private final long creationTime;

    public static <U> ContinuousCompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return new ContinuousCompletableFuture<>(CompletableFuture.supplyAsync(supplier));
    }

    private ContinuousCompletableFuture(CompletableFuture<T> baseFuture) {
        this.baseFuture = baseFuture;
        this.creationTime = System.nanoTime();
    }

    public Long getElapsedTime() {
        return (System.nanoTime() - creationTime) / 1000_000L;
    }

    public ContinuousCompletableFuture<Void> thenAcceptAsync(BiConsumer<? super T, Long> action) {
        CompletionStage<Long> elapsedTime = CompletableFuture.completedFuture(getElapsedTime());
        return new ContinuousCompletableFuture<>(baseFuture.thenAcceptBothAsync(elapsedTime, action), creationTime);
    }
}

First test shouldReturnElapsedTime with extracted ContinuousCompletableFuture variable works fine, but other shouldOperateWithOwnExecutionTime fails. Meanwhile, I prefer to see it in my future code neither extracted ContinuousCompletableFuture variable.

import java.util.concurrent.atomic.AtomicLong;
import lombok.extern.slf4j.Slf4j;
import org.junit.*;
import static org.junit.Assert.*;

@Slf4j
public class ContinuousCompletableFutureTest {

    private static final int DELAY = 1000;

    AtomicLong flag = new AtomicLong();

    ContinuousCompletableFuture<String> future;

    @Before
    public void before() {
        future = ContinuousCompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(DELAY);
            } catch (InterruptedException ex) {
                log.error("Error during ContinuousCompletableFuture execution", ex);
            }
            return "successfully completed";
        });
    }

    @Test
    public void shouldReturnElapsedTime() {
        future.thenAcceptAsync(s -> {
            long t = future.getElapsedTime();
            log.info("Elapsed {} ms to receive message \"{}\"", t, s);
            flag.set(t);
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            log.error("Error awaiting Test completion", ex);
        }

        assertTrue("Future completion should be delayed", flag.get() >= 0.75 * DELAY);
    }

    @Test
    public void shouldOperateWithOwnExecutionTime() {
        future.thenAcceptAsync((s, t) -> {
            log.info("Elapsed {} ms to receive message \"{}\"", t, s);
            flag.set(t);
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            log.error("Error awaiting Test completion", ex);
        }

        assertTrue("Future completion should be delayed", flag.get() >= 0.75 * DELAY);
    }
}

I assume that my issue lies in wrong thenAcceptBothAsync method usage.

Any suggestions?


原文:https://stackoverflow.com/questions/33080624
更新时间:2023-05-23 11:05

最满意答案

好吧, xlim不工作,但为什么不在xticks上留下1和1000呢?

plt.xticks([1, 1000])

okay, xlim is not working, but why not just leave 1 and 1000 on the xticks?

plt.xticks([1, 1000])

相关问答

更多
  • 好吧, xlim不工作,但为什么不在xticks上留下1和1000呢? plt.xticks([1, 1000]) okay, xlim is not working, but why not just leave 1 and 1000 on the xticks? plt.xticks([1, 1000])
  • 看来问题出在你的vectorToGeogr和spherical2vector函数中。 基于这些评论以及你正在旋转的极点,它看起来(?)像你打算有以下关系: x : east-west (east-positive) y : north-south (north-positive) z : up-down (down-positive) 然而,在假设数学坐标的地方,你已经混合了数学: x : towards the equator/prime-meridian intersection y : toward ...
  • 首先,我认为你必须将这些字符串映射为整数,然后matplotlib可以决定将这些点放在哪里。 labels = ['B','A','F','G','K','M'] mapping = {'B': 0,'A': 1,'F': 2,'G': 3,'K': 4,'M': 5} df = df.replace({'Spec Type Index': mapping}) 然后绘制散点图, fig, ax = plt.subplots() ax.scatter(df['Spec Type Index'], df['D ...
  • 每次更改要在图上显示的范围时,都会引发setExtremes事件。 它可以有几个来源: 按钮在范围选择器中单击 导航器中的手柄拖动 等等.. 事件的实际属性取决于其来源。 如果你使用console.log(e)输出事件,你会发现这两个来源并不相同: 按钮在范围选择器中单击 { trigger: "rangeSelectorButton", rangeSelectorButton: { text: "2Hour", type: "hour", ...
  • 使用matplotlib.gridspec.GridSpec非常简单 gs=GridSpec(3,3)创建一个3x3网格以放置子图 对于您的顶行和底行,我们只需要在该3x3网格上索引一个单元格(例如, gs[0,0]位于左上角)。 对于中间行,您需要跨越两列,因此我们使用gs[1,0:2] import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig=plt.figure(figsize=(16,12)) gs ...
  • 您需要在从.get_position()获取实际位置之前绘制画布。 这是因为由于纵横比相等,轴在绘制时改变尺寸和位置。 import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable matplotlib.rcParams.update({'font.s ...
  • 您可以使用BoundaryNorm ,如下所示: import matplotlib.pyplot as plt import matplotlib.colors import numpy as np x = np.arange(0, np.pi, 0.1) y = np.arange(0, 2*np.pi, 0.1) X, Y = np.meshgrid(x, y) Z = np.cos(X) * np.sin(Y) * 10 colors = [(1, 0, 0), (0, 1, 0), (0, 0, ...
  • 我假设您只想将刻度设置为等于['one', 'two', 'three'] ? 为此,您需要使用set_xticks()和set_xticklabels() : from PyQt5.QtWidgets import * from PyQt5.QtGui import * import matplotlib.pyplot as plt def pushButtonClicked(self): code = self.lineEdit.text() x=["one","t ...
  • 实际上这是一个非常好的问题! 我总是被这个困扰,但最后你的问题踢我终于解决了:-) 好吧,在这种情况下我们不能简单地做hist(x, xlim = c(100, 500), breaks = 9) ,因为breaks指的是x的整个范围,与xlim (换句话说,使用xlim )仅用于绘图,不用于计算直方图和设置实际中断)。 这是hist函数的一个明显缺陷,文档中没有简单的补救措施。 我认为最简单的方法是在进入hist函数之前 “xlim”值: x <- runif(1000, 0, 1000) # examp ...
  • 您可以在.tickValues()使用.tickValues()方法来准确指定您想要的刻度。 使用tickValues ,您可以提供一系列刻度,这些刻度恰好是图表上显示的刻度线。 你的轴看起来像这样: xAxis = d3.svg.axis().scale(xScale) .tickFormat("") .tickValues([1,2,3,4,5,6,7,8,9,10]) .orient("bottom"); 当然,如果您只有max和min值,则可能需要使用循环来填充数组,然后将最终数组作为参数传递给t ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。