繁体   English   中英

在独立java程序中调用rest web服务时的并发问题

[英]Concurrency issue while calling rest web service in standalone java programme

我正在尝试使用执行器框架使用固定线程池。 提交给执行器的每个可运行实例都是处理 java 结果集的工作线程。 对于结果集的每次迭代,我必须调用使用 oauth 令牌的 rest webservice。 oauth 令牌将在每 50 分钟后刷新一次,并且需要在提交给执行程序的所有可运行程序之间共享。我也在使用每 50 分钟后执行一次的预定执行程序,但有时它会被正确调用,而有些时间不是由于哪个其余 Web 服务失败,因为它在其标头中使用了过期的令牌。 我需要确保每 50 分钟后必须调用预定的服务而不会失败。 但我坚持这一点。 此外,我需要一些机制,在完成其余 Web 服务调用组之后,在迭代结果集时只应进行新的 Web 服务调用。

ThreadPoolExecutor executorPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
WorkerThread wt1=new WorkerThread(conn,Queries.getAddressInfo("AL"),oauth_token,restTemplate);
WorkerThread wt2=new WorkerThread(conn,Queries.getAddressInfo("AK"),oauth_token,restTemplate);
executorPool.execute(wt1);
executorPool.execute(wt2);

ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(new Runnable() {
    public void run()  {

        System.out.println("token service");

        String url="";
        try {
            url = WebServicePropertyFileReader.getOauthUrl()+String.format(urlToGetOauthToken, WebServicePropertyFileReader.getClientId(),
                    WebServicePropertyFileReader.getClientSecret());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Layer7Token token=restTemplate.postForObject(url, null, Layer7Token.class);
        GlobalTokenAccessor.oauth_token=token.getAccessToken();
    }
},
50,
TimeUnit.MINUTES);

有两个问题: schedule 只安排一次。 您应该使用 scheduleAtFixedRate 来安排定期任务。 不能保证线程会在 50 分钟内得到调度。 因此,您可能希望每 49 分钟左右安排一次刷新。 其次,您应该通过同步的写入和读取方法来控制对共享变量的访问。 否则,读取线程可能会读取不正确的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM