1

I have a file open and write situation that crashes with EOFException once in about 20-30 times, because the file is unavailable because some other process is writing to it.

Can I catch this exception, then somehow wait for the file write operation synchronously to end, so I can recurse the method?

File productJSON = getFileStreamPath("product" + "_" + getId() + ".json");
if (!productJSON.exists()) {
    productJSON = getFileStreamPath("product" + ".json");
}

InputStream jsonStringsFileInputStream;
try {
    jsonStringsFileInputStream = new FileInputStream(productJSON);

    HashMap<String, Map> that = new JSONToProductParser().convertThisToThat(jsonStringsFileInputStream);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

2 Answers2

1

You can check the file for write access before opening it.This is done with the canWrite() method.

Oracle Docs - File # canWrite

Also check out this solved question. It deals with the synchronized attribute.

Solved Question - Synchronized

Community
  • 1
  • 1
cgew85
  • 427
  • 3
  • 9
  • So what do I do if canWrite returns false? do I keep looping the check? So do I make all the methods that deal with this file synchronized? – Kaloyan Roussev Dec 02 '14 at 09:34
  • You can poll for a certain time or amount of tries,if it doesnt change its status throw an exception or handle it according to you needs.Regarding synchronization you might wanna read into this: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html – cgew85 Dec 02 '14 at 09:41
-1

You can use a handler to introduce delays in your code.

final Handler handler=new Handler();
handler.postdelayed(new Runnable(){
@override
public void run(){
//Do something after 5 seconds....your code here
     }
},5000);

write your code within the run method

archon92
  • 447
  • 3
  • 13
  • This didnt work, because when I call the same method from within the handler, the rest of the code that started this method doesnt wait for the second iteration but goes on instead – Kaloyan Roussev Dec 02 '14 at 09:33