开发者

Java Multi-threading and Asynchronous Http Request Handling

This is probably a very generic question but I will shoot anyway since I need honest advice. I have a very simple library which is mostly threadsafe due to most clases being immutable. However, I have 2-3 classes which are not and I cannot modify them.

This library is extensively used with a Async HTTP client. It works like this. The client is instantiated with an observer. The observer handles all the complete, fail or loading events. The observer also calls the necessary functions from this other lib.

I am using the Async HTTP client almost like it runs in a single thread with non-blocking io. However, underneath, the client uses thread pools.

My question is: if I make all the handler methods in the observer synchronized, will that resolve all other thread safety issues?

For example, we have the following setup.

Client -> calls methods from the
   Observer
      synchronized onLoaded -> calls thread unsafe code
      synchronized onError -> calls thread unsafe code
      synchronized onCompleted -> calls thread unsafe code

If this doesn't make sense, is it possible somehow to execute all the code within these methods on the main thread and as such achieve the non-blocking io design I am trying to follow?

CLAR开发者_开发知识库IFICATIONS: I know that the Async HTTP lib is thread based and blocking but the rest of the code is not... everything is based around event.


Other than adding the synchronized, check if those three (2) methods are not modifies class fields. if yes, you may use ThreadLocal.

Usage: uniqueNum is class field but it declares with ThreadLocal. So it is safe.

 import java.util.concurrent.atomic.AtomicInteger;

 public class UniqueThreadIdGenerator {

     private static final AtomicInteger uniqueId = new AtomicInteger(0);

     private static final ThreadLocal < Integer > uniqueNum = 
         new ThreadLocal < Integer > () {
             @Override protected Integer initialValue() {
                 return uniqueId.getAndIncrement();
         }
     };

     public static int getCurrentThreadId() {
         return uniqueId.get();
     }
 } // UniqueThreadIdGenerator


It should make it thread safe as long as the other lib does not has/call a unsafe-static method. This applies only if there are multiple Observers objects and they can be called parallely. If that is not the case, then it should be ok.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜