I m working in java. I have an application which will read & write one sample.txt file. And one more application which will also read & write to same file. And first application will run for every 1 minute as windows service. My doubt is now how, can make sure that both applications should r/w at the same time. Any suggestions plz.
Asked
Active
Viewed 80 times
-3
-
4See: http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible – kiheru Jul 18 '13 at 14:07
3 Answers
3
As you want to lock access from different application if i understand it right. You can use FileLock here an example

Moti Korets
- 3,738
- 2
- 26
- 35
-
2Here. This is the right answer. People nowadays reads questions too fast. – Doodad Jul 18 '13 at 14:11
1
You need to guard the file access code through synchronized block or methods. Learn more about synchronization here:
http://javarevisited.blogspot.in/2011/04/synchronization-in-java-synchronized.html

Juned Ahsan
- 67,789
- 12
- 98
- 136
0
Simples solution is to use the synchronized keyword.
public synchronized int i = 1;
in this way i can only be accessed from one thread at the time. But this is expansive! There are many concepts of synchronization, e.g. the monitor
Read this for more information: http://www.artima.com/insidejvm/ed2/threadsynch.html

Mirco
- 2,940
- 5
- 34
- 57