我是多线程的新手,我对这种方法是否线程安全感到困惑,因为我没有在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
传递给该方法(因此可以由不同线程共享)的对象是否实际上是线程安全的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句