Java. I have two threads. one will be continuously monitoring for some events and based on the events, it will be updating (addition or deletion) a file. the other thread which is a timer task event, will be updating the same file in regular intervals of time. I want the threads to update the file when the other thread is not accessing the file. I couldn't use locks as file updating code part is independent for each thread and in different java classes. how can i do so? thanks in advance.
3 Answers
You can use synchronization.
public synchronized void update() { .. .. .. } so only one thread access the method. Other will wait on the lock.
If you have add,update,delete method then,
private static Object LOCK = new Object(); public void update() { synchronized(LOCK) { .. .. .. } } public void add() { synchronized(LOCK) { .. .. .. } } public void delete() { synchronized(LOCK) { .. .. .. } } So Only one thread can able to edit/delete/add the file.
if one thread is adding , second thread is trying to delete then it will wait first thread to add.
4 Comments
Arun
If i use synchronized to add method, no two threads can add data to the file at the same time but a thread can be adding data to the file while the other thread can be deleting at the same time right?
Siva Kumar
If you have separate method for add and delete then you can use synchronized block.
Arun
thanks @SivaKumar. In between, how about reentrant locks? which one is safer?
Siva Kumar
@Arun javarevisited.blogspot.in/2013/03/… Pl see
synchronized void updateFILE { //Your operation here } So at a time one thread can perform opetation.. You can have look at here
Comments
Perhaps you could:
- Create a wrapper class around your unsafe file-updater-class.
- Make that wrapper class thread-safe by adding your synchronization or locks that clearly defines the critical sections and handle all exceptions appropriately (for example, unlock the critical section in a finally-block)
- Let the other threads call your wrapper class instead.
synchronizedfor the methods you need to lock, checkSiva Kumar'sanswer belowBufferedReader / BufferedWriter, then you will be implicitly using locks. theread()andwrite()methods use synchronization and lock on the passed Reader / Writer. Any particular reason for not wanting to use locks?