What if the 'dir' is not null? In that case, seems you don't have the write lock to "dir". Another way to do this is to use a while loop to guarantee that the current thread has the write lock of the deepest folder.