954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Too many threads invoking synchronized method

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block.

What is happen when too many threads (for the same object) for example 100 Threads invoke this method and want to send data?
In which order can the Threads be executed?
Is there any queueing or buffering here?
If there is buffering, how long does it take to release the buffering data?

private Lock sendMessageLock = new ReentrantLock();

public Response send(SMTInitiated data) {
<strong>synchronized </strong>(sendMessageLock) {
return send(data);
}
}
amjad277
Newbie Poster
8 posts since Jun 2008
Reputation Points: 10
Solved Threads: 1
 

1. All threads start to run
2. Some thread get LOCK on some exclusive object
3. Other threads which are requiring this LOCKED object will get into SLEEP
4. After thread in step 2 release LOCKED object, thread manager will NOTIFY all other threads which are SLEEPing and waiting for this LOCKED object.
5. These threads resume running, back to step 1.

So normally system can't not make sure which one is the next resuming thread.

OS have some rules to schedule tasks. But I think you could experiment to get some clue:

private Lock sendMessageLock = new ReentrantLock();

public Response send(SMTInitiated data, String threadM) {
      synchronized (sendMessageLock) {

            System.out.println(threadM);
            Thread.sleep(100) ;

            return send(data);
      }
}

public void main () {
    Thread t1 = new Thread(new Runnable(){
          public void run() {
               for (int i=0; i < 100000;i++) 
                  send(data, "t1");
          }
    });
    Thread t2 = new Thread(new Runnable(){
          public void run() {
               for (int i=0; i < 100000;i++) 
                  send(data, "t2");
          }
    });
    Thread t3 = new Thread(new Runnable(){
          public void run() {
               for (int i=0; i < 100000;i++) 
                  send(data, "t3");
          }
    });
    Thread t4 = new Thread(new Runnable(){
          public void run() {
               for (int i=0; i < 100000;i++) 
                  send(data, "t4");
          }
    });

    t1.start();
    t2.start();
    t3.start();
    t4.start();


}
yzg1236
Newbie Poster
4 posts since Jun 2008
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You