i am developing file lock concept in java. i am using two threads. first thread is in running state...second thread will wait untill first thread release... i cant make second thread will wait.. i am getting some exception...
i am getting exception like this
inside second try.....
inside second try----->sun.nio.ch.FileLockImpl[0:9223372036854775807 exclusive valid]
inside second try.....
Exception java.nio.channels.OverlappingFileLockException Inside finally.....
java.nio.channels.OverlappingFileLockException at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(Unknown Source)
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(Unknown Source)
at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
at java.nio.channels.FileChannel.tryLock(Unknown Source)
You do a tryLock() which throws if it can't obtain the lock immediately. Then in finally block you (commented out) attempt to release the lock even though you haven't obtained it (which is wrong, so commenting-out helps here). But if you succeed, then you end up not releasing the lock because thah line is commented out. You need to releas eteh lock only if tryLock() succeded.
Use lock() instead of tryLock(). Then the second thread would wait until the first thread releases the lock.
If you want to use tryLock(), then don't release it if you get the exception from tryLock() and release it if you don't get the exception.
Be advised that file locks are useless for threading purposes. They only work between different programs.
Joined: Oct 20, 2009
Thanks for your response...
Database stores internal and external results. The Internal results are stored against the one input and the External results are stored against the another input. So, i have to call the Stored procedure twice. Once with the one input and again with the another input to get internal and external results respectively.Those need to be accessed using sinle thread...if one use the thread other should wait unitl it finishes, second thread should check every 5 seconds whether first finishes .......... please provide sample code if possible.........
what concept i have to use other than synchronization......... give your suggestion... many thanks in advance
Joined: Mar 22, 2005
For starters, as Henry pointed out, the code does not create threads. You probably meant to do new Thread(t).start() instead of t.run().
Then -in order to achieve synchronization- all threads need to use the same object as the lock; for example, FileTest.class, not any local variable within the object.