synchronization issue with closing a stream while writing to it
changes to stop deadlocks