Niko Gamulin Niko Gamulin - 6 months ago 23
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);
//Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, portNumber);

try {
//Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
String message = packData();
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;

} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;

} finally {

} catch (Exception e) {
Log.e("TCP", "C: Error", e);

When the execution reaches the line
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.


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) {

I have to admit that why you're wanting to do this baffles me in this case...