Tuesday, August 4, 2009

synchornized groovy

Today I discovered the question:

I want to have a websites which fires calculations to a database server, but the controller should only execute one calculation at a time

how do you do this?

The first approach was to try to queue the ajax calls, which obviously won't work if two people run calculations at the same time.

So plan b was to use synchronized groovy code.



/**
* does the actual calculation
*/
def calculate_ajax = {

assert params.database != null, "you need to provide 'database' in the params object"
assert params.date != null, "you need to provide 'date' in the params object"
assert params.machine != null, "you need to provide 'machine' in the params object"
assert params.pattern != null, "you need to provide 'pattern' in the params object"
assert params.position != null, "you need to provide 'position' in the params object"

//needs to be synchronized so we don't kill the database server with this task
synchronized (LOCK) {
println new Date()
BinBaseQualityConnector.getQualityService().calculateSingleStandard(params.pattern, params.database, new Date(Long.parseLong(params.date)), params.machine, BinBaseQualityConnector.getKey())
render("<div class=\"after_complete\" style=\"width:${100 / BinBaseQualityConnector.getPattern(params).size()}%\"></div>")

}
}

static final def LOCK = "lock"


and a possible ajax call for this looks like this


<script type="text/javascript">
YAHOO.util.Event.onDOMReady(
function() {
new Ajax.Updater('${i}_${y}_${z}', '/quality-war/processing/calculate_ajax', {
method: 'get', frequency: 3,parameters:'date=${date.getTime()}&database=${database}&machine=${machine}&pattern=${pattern}&position=${z}'
});
});
</script>

No comments:

Post a Comment