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?
CLARIFICATIONS: 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.