Fix a race condition where flush() can be triggered before write()

.. when a handler overrides write() but not flush().
Merge remote-tracking branch: upstream/master