Francesco
Francesco

Reputation: 2382

Code from sequential to thread

I must say I have veeery little experience in working with threads and I would appreciate if someone could help me. I have this piece of code which basically asks for the state of all the machines located in a room:

private List< ListRow > fetchListRows( Model amtRoomMachinesListModel )
{
    Room room = RoomHelper.getRoomByDbId(...);

    List< ListRow > listRows = new ArrayList<>();

    for ( Machine machine : room.getRoomPCs() )
    {
        setMachineStatus( machine );

        if ( amtRoomMachinesListModel.getState() == null
                || amtRoomMachinesListModel.getState().equalsIgnoreCase( machine.getState().getLabel() ) )
        {
            ListRow listRow = new ListRow( false, machine );

            listRows.add( listRow );
        }
    }

    sortListRows( listRows );

    return listRows;
}


private void setMachineStatus( Machine machine )
{
    State retrievedMachineState = State.ERROR;
    String machineName = "";

    try
    {
        machineName = AMTCHelper.ip2MachineName( machine ); // executes a nslookup

        retrievedMachineState = AMTCHelper.retriveMachineState( retrievedMachineState, machineName );  // executes an external C program and read the response
    }
    catch ( IOException | InterruptedException | ParseException e )
    {
        throw new BRException( ExceptionType.AMTC_ERROR, "command", String.format(AMTCHelper.getRetriveMachineStateCommand(), machineName ) , "error", e.getMessage() );
    }

    machine.setState( retrievedMachineState );
}

As the response time of the request for the state is 4 to 10 seconds and the number of machines in a room can be more than 100, I thought it could be useful to use threads to "simultaneously" start the process over machines' list so that the overall process time would be sensibly shorter.

I forgot to say that I use java 7 (not 8).

Can someone tell me how can I convert my sequential code into a thread-safe - using one, please?

Upvotes: 0

Views: 56

Answers (1)

Guillaume Pansier
Guillaume Pansier

Reputation: 201

As svarog said, there are several implementation that come with Java 7.

in java.util.concurrent, you have for example the class Executor, which provides:

ExecutorService service = Executors.newFixedThreadPool(nbThreads);

Based on that, you can use java.util.concurrent.Future

for ( Machine machine : room.getRoomPCs() )
{ 
   Callable<State> process = new Callable<Integer>() {
       //whatever you do to retrieve the state
       return state;
   }

   // At this point, the process begins if a thread is available
   Future<State> future = service.submit(process);
 }

The process is ran on submit(). You could create this way a list of futures. When you call future.get(), the main thread hangs until you get a response.

Finally, I suggest you take a look at guava, there are a lot of pretty useful functionalities. Adding callback (onsuccess, on error) to a Future for example.

Upvotes: 1

Related Questions