Niko Gamulin Niko Gamulin - 5 months ago 17
Java Question

Threading in Java: How to lock an object?

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.

Answer

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...