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 extractedContinuousCompletableFuture
variable works fine, but othershouldOperateWithOwnExecutionTime
fails. Meanwhile, I prefer to see it in my future code neither extractedContinuousCompletableFuture
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
最满意答案
好吧,
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 ...
-
使用自定义滴答的散点图(Scatter plot with custom ticks)[2024-01-13]
首先,我认为你必须将这些字符串映射为整数,然后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 ...
-
如何在matplotlib颜色栏中创建自定义断点?(How can I create custom break points in a matplotlib colorbar?)[2023-10-29]
您可以使用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 ...
-
自定义轴刻度D3(Custom number of axis ticks D3)[2022-06-14]
您可以在.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 ...