Reputation: 445
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?
Upvotes: 0
Views: 71
Reputation: 781
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();
}
}
}
Upvotes: 1