Fix race hazard in cache. (cherry-picking from commit 07d1130563154af54c3452b511d1f8a96d9205e0)