Java局部变量线程安全



我是新的多线程,我很困惑,如果这个方法是线程安全或不,因为我没有做一个新的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;
        }

作为编写线程安全代码的一般规则,您必须关注可变共享状态。局部变量不是共享的,所以不用担心。

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

最新更新