moved logic of batch writing to writer, so it can do it under lock