当多个时间调用相同的方法时,取消方法调用 [英] Cancelling method calls when the same method is called multiple time

查看:151
本文介绍了当多个时间调用相同的方法时,取消方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这里可能有一个名字,但我不知道。所以我的第一个问题是知道这种技术的名称。



这里有一个例子:假设你正在网页上实现实时搜索。每当用户在搜索框中键入时,您将触发一个新的搜索查询,并且尽可能多地更新结果。
这是一个愚蠢的事情,因为你会发送比你实际需要的更多的查询。每2-3个字母发送一次请求或每100ms最多发送一次请求可能就足够了。



因此,一种技术可以安排在密钥后不久执行的查询是键入的,如果仍然有计划但未执行的查询,请取消它们,因为现在已经过时了。






更具体地说,在Java中解决这个问题有哪些特定的模式或图书馆?



我不得不在Swing应用程序中解决问题,我使用了ExecutorService,它返回了可以取消的ScheduledFutures。问题是我不得不为每个想要缓冲的方法调用手动创建一个Runnable,并跟踪每个未来以取消它。



我确定我不是第一个实现这样的人,所以在某个地方必须有一个可重用的解决方案可能在Spring中有注释和代理的东西?

解决方案

给出其他答案,经过一些搜索,似乎确实没有图书馆这就是我想要的。



我创建了一个并放在GitHub上。这个问题的未来读者可能会发现它很有趣。



https://github.com/ThomasGirard/JDebounce



我不认为这是非常好的,但至少它的作品可以声明地使用:

  @Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID,DebounceTest callback){}


I think there's probably a name for what I'm describing here, but I don't know it. So my first question would be to know the name of this technique.

Here's an example: suppose you're implementing live search on a web page. Everytime the user types in the search box, you fire a new search query, and the results are updated as often as possible. This is a stupid thing to do because you'll send much more queries than you actually need. Sending a request once per 2-3 letters or at most once per 100 ms is probably sufficient.

A technique is thus to schedule the queries to be executed soon after a key is typed, and if there are still queries that were planned but not executed, cancel them since they're obsolete now.


Now more specifically, are there specific patterns or librairies for solving this problem in Java ?

I had to solve the problem in a Swing app, and I used an ExecutorService, which returned ScheduledFutures that I could cancel. The problem is that I had to manually create a Runnable for each method call I wanted to "buffer", and keep track of each Future to cancel it.

I'm sure I'm not the first person to implement something like this, so there must be a reusable solution somewhere ? Possibly something in Spring with annotations and proxies ?

解决方案

Given the other answers, and after some searching, it seems there's indeed no library that does what I wanted.

I created one and put it on GitHub. Future readers of this question may find it interesting.

https://github.com/ThomasGirard/JDebounce

I don't think it's very good yet but at least it works and can be used declaratively:

@Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID, DebounceTest callback) { }

这篇关于当多个时间调用相同的方法时,取消方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆