multithreading - Scala Play thread -


i'm using scala / play2 framework / mongodb (reactivemongo) have function in request doing : find maximum value in collection, increase maximum number random, , save new value collection, , return new value.

def generatecode():future[string] = {   // find maximum   maximum = future[].... map { maxvalue =>       // increase maxvalue       newvalue = maxvalue + random       // save database   } } 

the problem want code 1 thread run @ time. because if 2 thread run same time, value con conflicted. example: thread 1: read max = 100, thread 2 read max = 100 thread 1: increase max = 105, thread 2 increase max = 102 thread 1: save 105 db, thread 2 save 102 db

finally maximum in db 102, in should 105. how can ?

as rule reactivemongo api , operations on future require implicit executioncontext in scope. can define single threaded execution context , use in class defined generatecode() method , in class call reactivemongo api.

import java.util.concurrent.executors  implicit val ec: executioncontext = executioncontext.fromexecutor(executors.newsinglethreadexecutor()) 

you can pass ec explicitly methods require implicit executioncontext. need make sure whole chain of asynchronous method calls uses same single threaded execution context.


Popular posts from this blog

Apache NiFi ExecuteScript: Groovy script to replace Json values via a mapping file -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -