java - How does a synchronized statement work in this case? -


assume have class this:

public class server {     public static void main(string[] args) {        map<integer, serverthread> registry = collections.synchronizedmap(new linkedhashmap<integer, serverthread>());        ...        while(true) {          socket socket = serversocket.accept();          serverthread serverthread = new serverthread(id, registry);          registry.put(id, serverthread);       }    } } 

then:

public class serverthread extends thread {     private map<integer, serverthread> registry;    private int id;     public serverthread(int id, map<integer, serverthread> registry) {       this.id = id;       this.registry = registry;    }     ...     private void notify() {       synchronized(registry) {          for(serverthread serverthread : registry.values()) {             serverthread.callsomepublicmethodonthread();          }       }          } } 

i want make sure registry doesn't modified while iterating on it. making synchronized map guarantee behavior? or need synchronized statement. synchronized statement behave expect to?

thanks

you need synchronized block around loop.

see javadoc details.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -