简体   繁体   中英

Only execute once in a while loop

I have a method to add objects to a queue and also check the queue size. If the queue size hits max capacity, an alarm will be raised and the queue will remove the first object. Following is the code

private SomeQueue queue;
private boolean raiseAlarmOnce = true;
private boolean alarmRaised;
private AlarmConnection alarmConnection;

void addToQueue(Object obj) {

     queue.add(obj);

     while (queue.size() > 1000) {
         queue.remove(); 

         if (m_raiseAlarmOnce) {
            // raiseAlarm mtheod will return boolean value to indicate 
            // the result of raising alarm
            m_alarmRaised = alarmConnection.raiseAlarm();
            raiseAlarmOnce = false;
         }
      }
      m_raiseAlarmOnce = true;

      if (m_alarmRaised) {
         alarmConnection.clear();
         m_alarmRaised = false;
      }
   }

If the queue size is bigger than 1000, the queue will continually delete obj and only raise the alarm once. If the alarm raised successfully, the alarm will be cleared. Just want to know any better way to do this?

if you need raise alarm once, when queue size is 1001, 1002 etc instead of one time for each iteration, raise alarm out of the while using a flag

i suggest use local variables when works with threads or singletons isntances

void addToQueue(Object obj) {

     queue.add(obj)
     boolean raisAlarm = false;

     while (queue.size() > 1000) {
         queue.remove(); 
         raisAlarm  = true;
      }


      if (raisAlarm) {
            // raiseAlarm mtheod will return boolean value to indicate 
            // the result of raising alarm
            boolean m_alarmRaised = alarmConnection.raiseAlarm();
            if (m_alarmRaised) {
              alarmConnection.clear();
            }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM