0

I have a problem understanding synchronized(){} in Java. Somehow I thought that synchronized(this) I locking THIS instance of the Class and if I wanna access an attribute OR calling a function of this particular instance from another thread, than this other thread has to wait until synchronized is over. somehow in this sample code it DOESNT work. I want Thread A to wait till Thread B does something and go on later.

public class A implements Runnable{
public void start(){
    Thread t = new Thread(this);
    t.start();
}
public void run(){
    B b = new B();
    b.start();

    //DO STUFF
    while(b.loaded){
        //WAIT FOR B DOING STUFF
    }

    //GO ON DOING STUFF
}
}

public class B implements Runnable {
public boolean loaded;
public B(){
    loaded = false;
}
public void start(){
    Thread thread = new Thread(this);
    thread.start();
}

public void run(){
    //DOING STUFF
    synchronized (this){
        loaded = true;
    }
    //DO OTHER STUFF
}

}

It works if I do a method called,

public synchronized boolean getLoaded(){return loaded;}

But why do the writing AND reading process have to be synchronized ? Shouldn't it be enough if the object is only locked while writing cause then the reading has to wait anyways? in the first example I expect the programming doing the following stuff:

Thread A is reading loaded variable.

Thread B wants to write loaded variable but its synchronized so it locks the object.

Thread A tries to read loaded variable but the object is locked so it waits.

Thread B writes the variable.

Thread B unlocks.

Thread A keeps reading.

I read a lot about this topic but I couldn't understand it like 100%. Wish someone could explain that simple project to me.

1 Answers1

1

You have a wrong understanding on what synchronize does, It is not locking the object which you use, but it uses that object as a semaphore to lock a piece of exeutable code. Your example:

synchronized (this){
    loaded = true;
}

just locks the one-liner "loaded = true". It prevents that another thread can enter the same line of code. It waits in the "synchronized(this)" statement until the first thread (which owns the semaphore) leaves the block, by releasing the semaphore.

Your problem is more how one thread can wait and be notified about events in other threads. There are quite some different techniques doing that. A modern one (java8) is to use a CompletableFuture. Another one, more at the roots of java, is the pair wait() and notify(), both are methods which each Object (and its derivetions) know. A simple example of the latter I have provided in this SO answer

Heri
  • 4,368
  • 1
  • 31
  • 51
  • I read 3 articles about synchronizing but no one mentioned that its only for the same object.. easy explanation but finally I understood what synchronization does ! thank you very much :)) ill have a look at wait and notify now. maybe this is gonna solve my problem :) – felixbreuer Oct 14 '17 at 19:51