The folks at Big Corp Inc. like to do things in very formal ways. All code is officially peer reviewed. Important code for key aspects of the system is reviewed by a manager. Only blessed tools may be used. The environment is to be pristine - regardless of cost. Following the rules takes precedence over efficiency.

David R. reported that in one particular system, the data was coming in way too fast. The message consumer was spawning a background thread for each inbound message. As volume rose, the number of threads that got spawned exceeded the capacity of the system, and NullPointerExceptions got thrown around like siding in a hurricane. The Master Architect decided that this problem was so important that he would fix it himself. Of course, since he was the apex predator, nobody would (could) review his code:

  public interface ThrottleDao {
    public long getNumberOfDataRows();
  }


  public class ThrottleDaoImpl implements ThrottleDao {
    @Override
    public long getNumberOfDataRows() {
      try (Connection        con = ...;
           PreparedStatement ps  = con.prepareStatement("select count(1) from TheSchema.TheTable");
           ResultSet         rs  = ps.executeQuery()) {
          rs.next();
          return rs.getLong(1);
      } catch (Exception e) {
        // log it
        return 0L;
      }
  }


  public class InboundMessageHandler extends Thread {
     private Session     session;
     private Queue       mqQueue;
     private ThrottleDao dao;

     // Assume everything is initialized

     @Override
     public void run() {
        while (true) {
           try {
               final Message msg = // read message from mqQueue

               long numRowsInDbBeforeTransaction = dao.getNumberOfDataRows();

               new Thread(new Runnable() {
                   @Override
                   public void run() {
                     // call another class to process: msg and commit to database
                   }
               }).start();

               // poll the database until the transaction commits 
               // before starting with the next message

               while (dao.getNumberOfDataRows() <= numRowsInDbBeforeTransaction) {
                  try {
                      Thread.sleep(10); // 10 milliseconds
                  } catch (InterruptedException ie) {
                    // do nothing
                  }
               }
           } catch (Throwable t) {
             // log it
           } // try
        } // while
     } // run
  } // class InboundMessageHandler

I wonded what would happen if the transaction had to be rolled back and no new row(s) ever got committed as a result?

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!