相关疑难解决方法(0)

如何为"InterruptedException"编写单元测试

为了实现100%的代码覆盖率,我遇到了一种需要单元测试代码块的情况InterruptedException.如何正确地测试这个?(请使用JUnit 4语法)

private final LinkedBlockingQueue<ExampleMessage> m_Queue;  

public void addMessage(ExampleMessage hm) {  
    if( hm!=null){
        try {
            m_Queue.put(hm);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

java unit-testing

12
推荐指数
3
解决办法
1万
查看次数

是否可以中断ExecutorService的特定线程?

如果我有一个ExecutorService向其提供Runnable任务的东西,我可以选择一个并中断它吗?
我知道我可以取消Future返回(也提到这里:how-to-interrupt-executors-thread),但我怎么能提出一个InterruptedException.取消似乎没有这样做(事件虽然它应该通过查看源,可能OSX实现不同).至少这个片段不打印'它!' 也许我误解了一些东西而不是自定义runnable获得异常?

public class ITTest {
static class Sth {
    public void useless() throws InterruptedException {
            Thread.sleep(3000);
    }
}

static class Runner implements Runnable {
    Sth f;
    public Runner(Sth f) {
        super();
        this.f = f;
    }
    @Override
    public void run() {
        try {
            f.useless();
        } catch (InterruptedException e) {
            System.out.println("it!");
        }
    }
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
    ExecutorService es = Executors.newCachedThreadPool();
    Sth f = new Sth();
    Future<?> lo …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice

6
推荐指数
1
解决办法
4967
查看次数

一旦我的线程中断,我怎么能中断RestTemplate调用?

我需要创建一个库,在其中我将具有同步和异步功能.

  • executeSynchronous() - 等到我有结果,返回结果.
  • executeAsynchronous() - 立即返回Future,如果需要,可在其他事情完成后处理.

我的图书馆的核心逻辑

客户将使用我们的库,他们将通过传递DataKey构建器对象来调用它.然后我们将使用该DataKey对象构造一个URL,并通过执行它来对该URL进行HTTP客户端调用,然后在我们将响应作为JSON字符串返回之后,我们将通过创建DataResponse对象将该JSON字符串发送回我们的客户.有些客户会打电话executeSynchronous(),有些人可能会打电话executeAsynchronous(),这就是为什么我需要在我的库中单独提供两种方法.

接口:

public interface Client {

    // for synchronous
    public DataResponse executeSynchronous(DataKey key);

    // for asynchronous
    public Future<DataResponse> executeAsynchronous(DataKey key);
}
Run Code Online (Sandbox Code Playgroud)

然后我有我DataClient实现上面的Client接口:

public class DataClient implements Client {

    private RestTemplate restTemplate = new RestTemplate();
    private ExecutorService executor = Executors.newFixedThreadPool(10);

    // for synchronous call
    @Override
    public DataResponse executeSynchronous(DataKey key) {
        DataResponse dataResponse = null;
        Future<DataResponse> future = null;

        try …
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice interrupted-exception resttemplate

5
推荐指数
2
解决办法
3719
查看次数