Question: I send a request to server via Volley; And after send, increase a variable that show number of requests.

```
VolleyGeneral.getInstance().addToRequestQueue(jsonObj,TAG);
numberOfReq++;

```

Then when I get the response, decrease that variable.

```
@Override
public void onResponse(JSONObject response){
    numberOfReq--;
}

```

On another side, i'm showing an image, using fade in animation for 2 seconds then I finish the activity and go to the next activity. 

But i want to wait for all the server responses before finishing the activity. So i write this part like it:

```
@Override
public void onAnimationEnd(Animation anim){
    while(numberOfReq == 0){
        numberOfReq = -1;
        startActivity(intent);
        finish();
        break;
    }
}

```

If server send the responses before 2 second, everything is Okey.

**But** if response is received after 2 second, the activity doesn't finish.

Answer: 
Maybe I'm not understanding the question, because the answer seems incredibly simple. Just set a flag whenever the activity is "ready to finish", and then check for this condition in `onResponse()` too. 

Either `onAnimationEnd()` or the last `onResponse()` will run first, and the second one should start the second activity. For example:

```
private boolean mReadyToProceed;

@Override
public void onAnimationEnd(Animation anim)
{
    if (numberOfReq == 0)
        startOtherActivityAndFinish();
    else
       mReadyToProceed = true;
}

@Override
public void onResponse(JSONObject response)
{
    numberOfReq--;
    if (mReadyToProceed && numberOfReq == 0)
        startOtherActivityAndFinish();
}

```

(Note: make sure that the decrement and comparison is not affected by other request threads finishing, possibly with locks or by using `AtomicInteger`).
You are aware of the fact that Volley creates and maintains multiple threads, right?

Increments/decrements are not thread safe operations. Instead use something like:

```
AtomicInteger numberOfReq = new AtomicInteger(0);

numberOfReq.incrementAndGet(); // ++

numberOfReq.decrementAndGet(); // --

```

Not sure this is the cause of your problem, but event if not - it's a bug waiting to happen.

EDIT:

Setting numberOfReq to be a volatile int will not solve the problem.

Volatile does not guarantee atomicity. it only guarantees that the next 
thread to read a variable will see its exact value after operations performed
by a prior thread.

Now, increment (and decrement) operation is in fact a triplet:

```
a = x;
b = a + 1;
x = b;

```

If atomicity is not forced on this calculation, e.g. by using AtomicInteger, 
nothing will stop another thread visiting even a volatile field in the middle of such calculation and basically do away with the increment-in-process.