如何在同一时间内多次调用方法

huangapple go评论65阅读模式
英文:

How to call method multiple times in the same time

问题

我需要编写一些测试,这些测试将同时多次调用我的方法,使用MvcMock或其他什么东西是否可能?

我想要实现与我在bash中使用curl&curl&curl(异步运行多个curl请求)所实现的相同结果 - 我的方法会抛出乐观锁定异常,因为每个请求都会修改同一实体,但是我所有的测试都是通过的。

我知道解决方案(使用PESSIMISTIC进行锁定),它也运行得很好,但是我不知道如何对其进行测试。

英文:

I need to write some test which will call my method multiple times in the same time, is it possible using MvcMock or something?

I want to achieve the same result as I achieved using curl & curl & curl in bash ( run multiple curl requests asynchronously ) - my method throws Optimistic locking exception because each request modify the same entity, but all my tests are green.

I know the solution ( locking with PESSIMISTIC ) and it works fine, but I have no idea how to test it.

答案1

得分: 1

有什么东西会阻止使用基本的Java多线程吗?
类似这样的:

ExecutorService EXEC = Executors.newCachedThreadPool();
List<Callable<String>> tasks = new ArrayList<>();
Callable<String> c = () -> {
    yourMethodCall();
    return "";
};
tasks.add(c);
tasks.add(c);
tasks.add(c);
List<Future<String>> results = EXEC.invokeAll(tasks);
英文:

Is there anything that blocks using basic Java multi threading?
Something like

    ExecutorService EXEC = Executors.newCachedThreadPool();
    List&lt;Callable&lt;String&gt;&gt; tasks = new ArrayList&lt;&gt;();
    Callable&lt;String&gt; c = () -&gt; {
        System.out.println(&quot;Hello&quot;);
        return &quot;&quot;;
    };
    tasks.add(c);
    tasks.add(c);
    tasks.add(c);
    List&lt;Future&lt;String&gt;&gt; results = EXEC.invokeAll(tasks);

(replace Sys out with call of your method)

huangapple
  • 本文由 发表于 2020年9月25日 23:16:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64066914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定