How to read and write data into same file simultaneously

后端 未结 2 1029
北荒
北荒 2020-12-10 21:00

I have read many a posts where-in they speak about reading and writing into the file NOT simultaneously using JavaME. I have a special use case scenarios wh

相关标签:
2条回答
  • 2020-12-10 21:38

    Your first problem is that you are setting writtenCharsLen before you write the data. If your read thread sees it being non-zero before the write thread actually writes it, you have a problem. Move writtenCharsLen = str.length after the write.

    Another problem I see in your sample is that the threads never yield control. They will be CPU hogs.

    0 讨论(0)
  • 2020-12-10 21:57

    I will attack this problem:

    Present Undesired Result: The read and write threads are showing running sop's for read and write. The read thread is reading from the position the writing thread has written. I am not facing any exception in this code but the result is undesired. I have also tried synchronizing read and write streams but that is throwing IllegalMonitorStateException.

    If you have synchronized the access using monitors i.e. the reader calls someObject.wait() and the writer calls someObject.notify(), remember that you have to wrap these calls in a synchronized block on someObject:

    synchronized(someObject) {
        someObject.wait();
    }
    
    
    synchronized(someObject) {
        someObject.notify();
    }
    

    This is the cause for IllegalMonitorStateException.

    0 讨论(0)
提交回复
热议问题