The following Function is executing in its own thread:
private void doSendData() { try { //writeToFile(); // just a temporary location of a call InetAddress serverAddr = InetAddress.getByName(serverAddress); serverAddr.wait(60000); //Log.d("TCP", "C: Connecting..."); Socket socket = new Socket(serverAddr, portNumber); socket.setSoTimeout(3000); try { //Log.d("TCP", "C: Sending: '" + message + "'"); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); String message = packData(); out.println(message); Log.d("TCP", "C: Sent."); Log.d("TCP", "C: Done."); connectionAvailable = true; } catch(Exception e) { Log.e("TCP", "S: Error", e); connectionAvailable = false; } finally { socket.close(); announceNetworkAvailability(connectionAvailable); } } catch (Exception e) { Log.e("TCP", "C: Error", e); announceNetworkAvailability(connectionAvailable); } }
When the execution reaches the line serverAddr.wait(60000)
it throws an Exception:
java.lang.IllegalMonitorStateException: object not locked by thread before wait()
Does anyone know how to lock an object or a function in order to prevent the concurrency? I've tried to add a Lock object:
private final Lock lock = new ReentrantLock();
and the line
boolean locked = lock.tryLock();
at the beginning of function but it didn't work.
Every object in Java has a unique lock. If a thread wants to execute a synchronized method on a given object, first it has to get a lock of that object. Once thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
synchronized keyword can be used only with methods and code blocks. These methods or blocks can be static or non-static both. When ever a thread enters into Java synchronized method or block it acquires a lock and whenever it leaves synchronized method or block it releases the lock.
In order to call wait() on an object, you have to hold the synchronized lock on that object (though the lock is actually released while the thread is waiting):
synchronized (serverAddr) { serverAddr.wait(); }
I have to admit that why you're wanting to do this baffles me in this case...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With