richardaum
richardaum

Reputation: 6777

Synchronism and Threads

Well,

Imagine this:

synchronized (dataStorage) {
    dataStorage.add(hashMap);
    submitDataToServer();   
}

Also here, the method submitDataToServer()

private synchronized void submitDataToServer()
{
    if(dataStorage.size() > 0)
    {
        final HashMap<String, Object> hashMap = dataStorage.peek();
        HttpWebRequest webRequest = new HttpWebRequest(context, ServicesName.getTravelServiceFullUrl(), false, hashMap) 
        {   
            @Override
            public void onSuccess(String result) 
            {
                dataStorage.remove(hashMap);
                if(dataStorage.size() > 0)
                    submitDataToServer();
            }

            @Override
            public void onError(String result) 
            {
                new Handler().postDelayed(new Runnable() {  
                    @Override
                    public void run() {
                        submitDataToServer();
                    }
                }, tryAgainDelay);
            }
        };

        webRequest.execute();
    }
}

My question is about syncronization:

1) the calling to submitDataToServer() is under a synchronized block passing dataStorage object. When callback onSuccess is called, dataStorage still is under a synchronized scheme?

2) onError method starts an inner thread. Would dataStorage still be under a synchronized scheme?

Upvotes: 0

Views: 72

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

If your webRequest.execute() does not complete immediately, but rather blocks until it's time to call onSuccess/onError, then these methods will be called within the same synchronized block, but it will also defeat the entire purpose of having such a circuitous, callback-based API, whose primary purpose is to allow asynchrony.

Therefore, either your methods will not be called while holding a lock on dataStorage, or else they will but you are using the wrong kind of API to achieve that.

Upvotes: 2

Related Questions