在ListenableFuture中执行post任务不起作用

时间:2013-08-17 17:26:20

标签: java multithreading asynchronous guava

当我尝试asyn上传文件时使用ListenableFuture,但它不起作用。 如果它是syn,它可以正常工作。

ListenableFuture不支持将帖子执行到远程?我发现使用URL.openStream()的样本可以正常工作。

  private void asynUploadFileToRemote(final String uptoken, final String key, final File file, final PutExtra extra) {
    final ListenableFuture<String> future = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            logger.info("starting to upload file");
            // here is to upload a file to remote.
            PutRet putRet = IoApi.put(uptoken, key, file, extra);
            logger.info("end to upload file"); //this log never excute.
            return putRet.getKey();
        }
    });

    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                //recerve nothing here
                String key = future.get();
                logger.info("uploadkey:" + key);
            } catch (InterruptedException e) {
                logger.error("Interrupted", e);
            } catch (ExecutionException e) {
                logger.error("Exception in task", e.getCause());
            }
        }
    }, MoreExecutors.sameThreadExecutor());
}

IoApi.put:只需上传文件。

public static PutRet put(String uptoken, String key, File file,
                         PutExtra extra) {

    if (!file.exists() || !file.canRead()) {
        return new PutRet(new CallRet(400, new Exception(
                "File does not exist or not readable.")));
    }
    if (key == null) {
        key = UNDEFINED_KEY;
    }

    MultipartEntity requestEntity = new MultipartEntity();
    try {
        requestEntity.addPart("token", new StringBody(uptoken));
        FileBody fileBody = new FileBody(file);
        requestEntity.addPart("file", fileBody);
        requestEntity.addPart("key", new StringBody(key));

        if (extra.checkCrc != NO_CRC32) {
            if (extra.crc32 == 0) {
                return new PutRet(new CallRet(400, new Exception("no crc32 specified!")));
            }
            requestEntity.addPart("crc32", new StringBody(extra.crc32 + ""));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new PutRet(new CallRet(400, e));
    }

    String url = Config.UP_HOST;
    CallRet ret = new Client().callWithMultiPart(url, requestEntity);
    return new PutRet(ret);
}

0 个答案:

没有答案