Java局部变量Thread Safety

时间:2016-10-25 06:33:11

标签: java multithreading thread-safety

我是多线程的新手,如果这个方法是线程安全的,我很困惑,因为我没有在HttpURLConnection conn上做新的................. .....................

      protected byte[] someMethod(Authenticator authenticator, String url, boolean doPost) throws Exception {
    try {
      URL aUrl = new URL(url);
      strBldr = new StringBuilder();
      AuthenticatedURL.Token token = new AuthenticatedURL.Token();
      TestConnectionConfigurator connConf = new TestConnectionConfigurator();
      AuthenticatedURL authUrl = new AuthenticatedURL(authenticator, connConf);
      HttpURLConnection conn = authUrl.openConnection(aUrl, token);
      if (!connConf.invoked)
          throw new IOException("failed to invoked");
      String tokenStr = token.toString();
      if (doPost) {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
      }
      conn.setRequestProperty("Accept", "application/octet-stream");
      conn.setDoOutput(true);
      conn.connect();

      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

          BufferedInputStream in = new BufferedInputStream(
                            conn.getInputStream());

            ByteArrayOutputStream byteArraySt = new ByteArrayOutputStream();
               int counter;
               while ((counter = in.read()) != -1) {
                   byteArraySt.write(counter);
               }
               byte [] bArray = new byte[byteArraySt.toByteArray().length];
               bArray = byteArraySt.toByteArray();


            in.close();
            return bArray;
        }

1 个答案:

答案 0 :(得分:0)

作为编写线程安全代码的一般规则,您必须关注可变共享状态。本地变量不会被共享,因此它们不是一个问题。

您的代码应该是线程安全的,但是您应该检查传递给该方法的authenticator对象(因此可以由不同的线程共享)是否实际上是线程安全的。