FabianTe
FabianTe

Reputation: 649

Preventing usage of multiple methods by several threads simultaneously

I'm writing a server for a chat room and have the following problem. I have methods for adding, removing and manipulating users. Simplified it looks like this:

User[] users = new User[8];

public synchronized void addUser(User u) {
    for (int i = 0; i < 8; i++)
        if (users[i] == null)
            users[i] = u;
}

public synchronized void broadcast(String s) {
    for (User u: users)
        u.sendMessage(s);
}

public synchronized void removeUser(User s) {
    for (int i = 0; i < 8; i++)
        if (users[i] == s)
            users[i] = null;
}

I am unsure if this is enough. I want to make this thread safe. An example: I have Thread A and B, both have acces to these methods. When Thread A calls the broadcast methods, Thread B should not be able to use any of these methods. Is it enough to put the synchronized modifier there? I know that one should be carefull when using it because it slows down the program because threads have to wait, but my program is small enough that speed isn't important.

Upvotes: 2

Views: 806

Answers (3)

Keerthivasan
Keerthivasan

Reputation: 12890

The code is synchronized on the particular instance only. This will allow only a single thread to invoke the method on it's instances in a particular time. i.e. per thread per method per instance at any point of time. To answer your question,

When Thread A calls the broadcast methods, Thread B should not be able to use any of these methods. Is it enough to put the synchronized modifier there?

Yes,the code is safe enough that it will not allow Thread B to invoke any of the methods on the instance in the same time until the lock is released by Thread A

Upvotes: 1

timgeb
timgeb

Reputation: 78790

In addition to the previous answers, for thread-unsafe operations you can use a lock. Here's a quick example:

import threading

theLock = threading.Lock()

def foo():
    global theLock

    #acquire the lock, thread will wait until no other thread has the lock
    theLock.acquire()

    #do something
    bar()   

    #release lock so that other threads may acquire it, if other thread is waiting for lock it may be launched immediately
    theLock.release()

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Provided that all three methods belong to the same class, and that all threads have the same instance of that class, synchronized is enough to ensure that only one of these three methods can be executing at any instance of time. If another thread tries running one of these three methods while a thread is executing, that second thread would automatically wait for the method to complete.

Upvotes: 2

Related Questions