Optimize the fix for takeLast and handle the race condition