devxlogo

How to Keep Track of Number of Threads or Connections

How to Keep Track of Number of Threads or Connections

Question:
I have a server application listening for clientapplets to connect. The server spawns a new thread each timea connection to a client is established. I want to keeptrack, i.e. count the number of clients connectedand output it to a textfield in a frame. I amnot sure how Java handles shared data among threads so myquestion is: How does one keep track of the number of threadsor connections? I want the number of threads to be displayed ina single frame; I tried something, but a new window is createdeach time a new thread is spawned.

Answer:
Since all threads share the same address space, the simplest solutionis to create a count monitor in the parent thread. Each time theparent thread creates or starts a child thread, it (or the child) incrementsthe count monitor. Each time it stops a thread, it decrements the countmonitor. The count monitor can be passed as a parameter to eachchild thread so it too can increment and decrement it, but in thiscase, access to count needs to be synchronized.

(Note: Java provides a method Thread.activeCount(), whichreturns thenumber of active threads. Unfortunately, this doesn’t get decrementedwhen threads are stopped.)

*/class CountMonitor {   private  int count = 0; // = # of active threads   public synchronized void updateCount(int amt) {      // don’t decrement a zero count      if (count 

devx-admin

Share the Post: