Demand
In recent projects such a feature, want the app to listen to the Android file system, when the file Create/modify/detele, the app receives notification, the corresponding change information to tell the server
Solutions for demand
When we take photos with our mobile phone, we save the photo files in the SDcard Dcim folder. When the file is generated, we receive the create/modify/write_close message, and we are going to send the message to the server after write_close, so that when we receive the create message, we need to block the current thread. Call Notifyall to open the blocked thread until the Write_close message is received.
Problem
The problem is that after we receive the Write_close message, we call SetState (true), but the value of Ischange does not change immediately, but after a few seconds it is changed.
Take a look at the core code
while (Count > 0) { //block thread code, code abbreviation: Loop synchronized (this) {if (!ischange) {///when Ischange does not become true, wait until the write is received _close message, call SetState (True) try {log.d (Log_tag, "sleeping ..."); this.wait (+) ; The original call here is TimeUnit.MILLISECONDS.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} Continue;}} //... Omit code sendmsg2server (); Break after closing}
Public synchronized void SetState (Boolean ischange) {This.ischange = True;this.notifyall ();//The original is not added this sentence, after the change to wait (1000) , Call Notifyall ()}
Problem Solving Solutions
Change TimeUnit.MILLISECONDS.sleep (1000) to wait (1000) and Notifyall () in SetState (true).
The root of the problem
Synchronization blocks are used in if (!ischange) and SetState (), and the synchronous lock is this. When we call Sleep (1000), the loop does not hand over the sync lock , but instead holds the lock until 1 seconds of sleep is completed, when the SetState () and the loop will compete for the This lock, setState () does not compete to this lock is very normal, As long as setstate () does not compete to lock, the loop will sleep for 1 seconds, which will result in the printing of several sentences log.d (Log_tag, "sleeping ..."), after which the Ischange value is changed.
When we change the code to wait (1000), the loop locks the lock out immediately , SetState () Gets the lock, changes the value of the ischange immediately, and notifies the loop so that it can enter the code of the Back Sendmsg2server ().
The difference between the wait and sleep methods holding lock states in [Android] sync block code