Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5999317
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:32:07+00:00 2026-05-23T00:32:07+00:00

I’m designing a concurrent Java application that reads data from various medical devices available

  • 0

I’m designing a concurrent Java application that reads data from various medical devices available on the hospital Intranet.

I’ve read “Java concurrency in practice – Brian Goetz…” to understand how to do stuff, but I think I’m still missing something.

Here’s a quick simple diagram of what I’m trying to do and there’s some code snippet below..

Worker threads (MedicalDeviceData instances) continuously read data from medical devices and make it available for the MedicalDeviceWorkManager, who in turn supplies it to the end user.
The worker threads keep reading data infinitely (ideally) and there’s no “work completed” situation in my scenario.
Moreover, user can choose to Start All devices or start a specific device or stop a device as and when he wishes.

Below is code snippet (compiles but not tested) of how I would implement it.

MedicalDeviceWorkManager – Spawns the worker threads and manages them.

MedicalDeviceData – Worker thread gets data from medical devices infinitely and updates this instance of this class.

Mainly look at startDevice, stopDevice and run methods.

You’ll obviously notice that I’m not using ThreadPoolExecutor and Future and that I just rolled my own implementation here.

As future.get blocks till a work is completed, it doesnt make sense for my case, because my worker thread never “completes” the task…its just an infinitely ongoing task…

QUESTION:How do I change the implementation shown below to a more standardized one so that I could make better use of java.util.concurrent package (ThreadPoolExecutor/Future).

Any other better design pattern I should look at?

public class MedicalDeviceWorkManager {

  private ThreadGroup rootThreadGroup = null;
  Hashtable<String, MedicalDeviceData> deviceObjs = new Hashtable<String, MedicalDeviceData>();

  public void manageMedicalDevices() throws InterruptedException  {

    String[] allDevices={"Device1","Device2","Device3","Device4"};

    //-- Start all threads to collect data
    for(String deviceToStart:allDevices){
      this.startDevice(deviceToStart);
    }

    //-- Stop all threads 
    for(String deviceToStop:allDevices){
      this.stopDevice(deviceToStop);
    }

    //-- Start on request from user
    String deviceToStart="Device1";
    this.startDevice(deviceToStart);

    //-- Stop on request from user.
    String deviceToStop="Device1";
    this.stopDevice(deviceToStop);

    /* 
     * Get Data and give it to client 
     * This is happening via a separate TCP port
     * */
    while(true){
      for(String deviceName:allDevices){
        if(deviceObjs.get(deviceName)!=null){

          ConcurrentHashMap<String,BigDecimal> devData=deviceObjs.get(deviceName).getCollectedData();

          //--Loop and send data to client on TCP stream
          ;
        }
      }//-- loop the devices
    }//-- infinite
  }

  //-- Start the device to start acquiring data using a worker thread
  private void startDevice(String deviceName){
    //-- Get Device instance
    MedicalDeviceData thisDevice=deviceObjs.get(deviceName);
    if(thisDevice==null){
      thisDevice=new MedicalDeviceData(deviceName);
      deviceObjs.put(deviceName, thisDevice);
    }

    //-- Create thread to start data acquisition 
    //-- Start if not being processed already (Handle what if thread hung scenario later)
    if(this.getThread(deviceName)==null){
      Thread t=new Thread(thisDevice);
      t.setName(deviceName);
      t.start();          
    }
  }


  //-- Stop the worker thread thats collecting the data.
  private void stopDevice(String deviceName) throws InterruptedException {
    deviceObjs.get(deviceName).setShutdownRequested(true);
    Thread t=this.getThread(deviceName);
    t.interrupt();
    t.join(1000);
  }

  private Thread getThread( final String name ) {
    if ( name == null )
        throw new NullPointerException( "Null name" );
    final Thread[] threads = getAllThreads( );
    for ( Thread thread : threads )
        if ( thread.getName( ).equals( name ) )
            return thread;
    return null;
  }

  private ThreadGroup getRootThreadGroup( ) {
      if ( rootThreadGroup != null )
          return rootThreadGroup;
      ThreadGroup tg = Thread.currentThread( ).getThreadGroup( );
      ThreadGroup ptg;
      while ( (ptg = tg.getParent( )) != null )
          tg = ptg;
      return tg;
  } 

  private Thread[] getAllThreads( ) {
    final ThreadGroup root = getRootThreadGroup( );
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean( );
    int nAlloc = thbean.getThreadCount( );
    int n = 0;
    Thread[] threads;
    do {
        nAlloc *= 2;
        threads = new Thread[ nAlloc ];
        n = root.enumerate( threads, true );
    } while ( n == nAlloc );
    return java.util.Arrays.copyOf( threads, n );
  }

}//-- MedicalDeviceWorkManager




public class MedicalDeviceData implements Runnable{

  //-- Data Collected from medical device
  private final ConcurrentHashMap<String,BigDecimal> collectedData=new ConcurrentHashMap<String,BigDecimal>();

  //-- Set by Thread Manager to request a shutdown..after which it should interrupt the thread
  private AtomicBoolean shutdownRequested;

  //-- Simple data Counter
  private AtomicInteger dataCounter=new AtomicInteger(0);

  //-- Device Name
  private String thisDeviceName;

  public void run() {

    //-- Initialize I/O for the device
    ;

    while(!this.getShutdownRequested()){
      try{
        //-- just to compile the code
        Thread.sleep(0);

        //-- perform I/O operation to get data from medical device
        ;

        //-- Add data into the ConcurrentHashMap...Both key and value are immutable.
        collectedData.put("DataKey", new BigDecimal("9999"));

        //-- data counter
        dataCounter.getAndIncrement();

      }
      catch(InterruptedException ie){
        if(this.getShutdownRequested()){
          return;
        }
        //throw new InterruptedException();
      }
    }

  }//-- run

  public MedicalDeviceData(String thisDeviceName){
    this.thisDeviceName=thisDeviceName;
  }

  /**
   * @return the shutdownRequested
   */
  public boolean getShutdownRequested() {
    return this.shutdownRequested.get();
  }


  /**
   * @param shutdownRequested the shutdownRequested to set
   */
  public void setShutdownRequested(boolean shutdownRequested) {
    this.shutdownRequested.set(shutdownRequested);
  }


  /**
   * Both key and value are immutable, so ok to publish reference.
   * 
   * @return the collectedData
   */
  public ConcurrentHashMap<String, BigDecimal> getCollectedData() {
    return collectedData;
  }


  /**
   * @return the dataCounter
   */
  public AtomicInteger getDataCounter() {
    return dataCounter;
  }

}
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T00:32:07+00:00Added an answer on May 23, 2026 at 12:32 am

    Rob’s comment got me thinking about a possible alternative solution. You can utilize an ExecutorService in which a start would submit to said service. When the runnable completes and pause or stop were not selected then the callable will re submit itself to the service. So you will now effectively have only a pre determined number of threads running with sequential consistency amongst work execution.

    A lot of the code is still the same just underlying execution would differ.

    public class MedicalDeviceWorkManager {
    
       private ConcurrentHashMap<String, DelegatedWorker > devices = new ConcurrentHashMap<...>();
    
       private final ExecutorService worker = Executors.newFixedThreadPool(10);
    
       public void registerDevice(String device, Runnable singleUnitOfWork){
             devices.put(device,new DelegatedWorker (singleUnitOfWork));
       } 
    
       public void startDevice(String device){
            devices.get(device).startDevice();
       }    
       public void stopDevice(String device){
            devices.remove(device).stopDevice();
       }    
       public void pauseDevice(String device){
            devices.get(device).pauseDevice();
       }    
       private class DelegatedWorker { 
          private final Runnable r;
          private volatile Future<?> running;
          DelegatedWorker (Runnable r) {this.r =r ;}
    
           public void startDevice(){
                if(running != null){
                   running = worker.submit(new Callable<Object>(){
    
                    public Object call(){
                         if(Thread.interrupted())return null;
                            r.run();
                         if(Thread.interrupted())return null;
    
                         return worker.submit(this);
                       }
                  });
                 }           
           }    
           public void stopDevice(){
                pauseDevice();
           }    
           public void pauseDevice(){
              if(running!=null){ 
                  running.cancel(true);
                  running = null;
               }
           }    
         }
       }
    

    Keep in mind here, instead of a volatile Future, you may want one which you lock around because of the compound function included in pauseDevice()

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.