Scala: Return but don't stop executing - scala

It's a simple thing but i have no idea how i can do it in Scala. I want to return a true in a Future. I use the twitter Future. But I want to return it as fast as possible. Like this:
def saveOrUpdate(pageImpression: PageImpressions): com.twitter.util.Future[Boolean] = {
return com.twitter.util.Future.value(true)
count += 1
println(count)
}
But this wouldn't work. How I can return something but also continuing the execution? It's a HTTP service. The return value will returned to the HTTP client.

I am not sure I understand what exactly you are looking for, but it seems like you want something like this:
def saveOrUpdate(pageImpression: PageImpressions) {
FuturePool.unboundedPool {
count += 1
println(count)
}
Future.value(true)
}
It puts a job of incrementing the count and printing it out on a background thread, and returns an immediate future with true.
This is a wrong thing to do in more ways then one however. I don't recommend it at all. First of all, it has unsynchronized access to a mutable variable, which will cause big problems.
And secondly, it returns true unconditionally, regardless of how (or whether) the underlying operation actually completed. If you don't care about result of the execution, you should return (future of) Unit, not Boolean.

Related

How to do a `getOrElseComplete` on `Promise`?

Does it make sense to have an operation like getOrElseComplete that tries to complete a Promise with a value but, if the Promise is already completed, returns the existing completed value instead. Here's a sample implementation:
implicit class PromiseOps[T](promise: Promise[T]) {
def getOrElseComplete(value: Try[T]): Try[T] = {
val didComplete = promise.tryComplete(value)
if (didComplete) {
value
} else {
// The `tryComplete` returned `false`, which means the promise
// was already completed, so the following is safe (?)
promise.future.value.get
}
}
}
Is this safe to do? If not, why not? If so, is there a way to do this directly (eg. without relying on questionable things like _.value.get) or why isn't there such a way in the standard library?
From your comments it seems to me that this is a valid solution for your problem but I also feel that a method like this doesn't belong in Promise API because Promise is supposed to be only a settable "backend" of its Future.
I'd prefer to have a completely separate function which could look like this:
def getOrComplete[T](promise: Promise[T], value: Try[T]): Try[T] =
promise.future.value.getOrElse {
if (promise.tryComplete(value)) value
else getOrComplete(promise, value)
}
The recursive call may seem weird - it serves two purposes:
it protects against a race condition where some other thread completes the future just before we call tryComplete
it avoids usage of .value.get on the Future
You might also want to pass value as a by-name parameter to avoid evaluating it when the Promise is already completed.
This operation does what it promises. It may make more sense to take value by name, and don't try to complete if already completed, maybe something like
def getOrElseComplete(value: => Try[T]): Try[T] = {
if (!promise.completed) {
promise.tryComplete(value)
}
promise.future.value.get
}
It's kinda dodgy though. Sharing a promise and having multiple places where it might be completed sounds like a difficult to maintain design, and one has to ask what's happening with the other path that might still complete the Promise? Shouldn't something be cancelled there?

How to implement non chronological backtracking

I'm working on a CDCL SAT-Solver. I don't know how to implement non-chronological backtracking. Is this even possible with recursion or is it only possible in a iterative approach.
Actually what i have done jet is implemented a DPLL Solver which works with recursion. The great differnece from DPLL and CDCL ist that the backracking in the tree is not chronological. Is it even possible to implement something like this with recursion. In my opionion i have two choices in the node of the binary-decision-tree if one of to path leads i a conlict:
I try the other path -> but then it would be the same like the DPLL, means a chronological backtracking
I return: But then i will never come back to this node.
So am i missing here something. Could it be that the only option is to implement it iterativly?
Non-chronological backtracking (or backjumping as it is usually called) can be implemented in solvers that use recursion for the variable assignments. In languages that support non-local gotos, you would typically use that method. For example in the C language you would use setjmp() to record a point in the stack and longjmp() to backjump to that point. C# has try-catch blocks, Lispy languages might have catch-throw, and so on.
If the language doesn't support non-local goto, then you can implement a substitute in your code. Instead of dpll() returning FALSE, have it return a tuple containing FALSE and the number of levels that need to be backtracked. Upstream callers decrement the counter in the tuple and return it until zero is returned.
You can modify this to get backjumping.
private Assignment recursiveBackJumpingSearch(CSP csp, Assignment assignment) {
Assignment result = null;
if (assignment.isComplete(csp.getVariables())) {
result = assignment;
}
else {
Variable var= selectUnassignedVariable(assignment, csp);
for (Object value : orderDomainValues(var, assignment, csp)) {
assignment.setAssignment(var, value);
fireStateChanged(assignment, csp);
if (assignment.isConsistent(csp.getConstraints(var))) {
result=recursiveBackJumpingSearch(csp, assignment);
if (result != null) {
break;
}
if (result == null)
numberOfBacktrack++;
}
assignment.removeAssignment(var);
}
}
return result;
}

Break out of double foreach in Scala

I have to return true or false based on field value in inner set item. My loops is as follow
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) true
})
})
false
It shoudld break and return true as soon as I have true on available but its returning false all the time. Any suggestion?
I don't have your dataset to work with, but perhaps this might do it.
myChoice.category.exists(_.flavours.exists(_.available))
Scala doesn't have continue or break. Because it is a fully functional language, every expression (including a loop) must have a value. Moreover, it tries to break out of the imperative style of initializing variables and mutating them over the course of a loop. Instead, scala encourages you to use a functional style, i.e. use methods that apply to data structures as a whole to transform/search for the desired result.
For your case, you're clearly looking to see if any of the flavors have their available field set to true. Thus you could flatMap the whole nested collection to a List of Boolean, and take the or of the whole collection:
val anyAvaliable = myChoice.category.flatMap(a => a.flavours).reduce( (flavour1,flavour2) => flavour1.available || flavour2.available)
jwvh's solution is even more concise. There are many ways of accomplishing essentially the same thing. Don't fight the language, have it fight for you!
Disclaimer: the below solution is provided for completeness, but jwvh's answer should be preferred for this case and generally speaking there are better alternatives. In particular, note that return from inside a lambda is implemented using exceptions, so 1) it may perform much worse than normal method calls; 2) if you are careless you can accidentally catch it.
If this is the last thing you need to do in the method, you can just use return:
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) return true
})
})
false
If it isn't, you can extract a method (including a local one):
def foo = {
...
val myChoice = ...
def hasAvailableFlavorsMethod() = {
myChoice.category.foreach(category => {
category.flavours.foreach(flavour=> {
if (flavour.available) return true
})
})
false
}
val hasAvailableFlavors = hasAvailableFlavorsMethod()
...
}

Proper usage of cache.putIfAbsent() in Cache2k

I am wondering how to work with the putIfAbsent() method when using the Cache2k cache. In the ConcurrentHashMap for example, one works with the method like this:
Set<X> set = map.get(name);
if (set == null) {
final Set<X> value = new HashSet<X>();
set = map.putIfAbsent(name, value);
if (set == null) {
set = value;
}
}
(Copied from Should you check if the map containsKey before using ConcurrentMap's putIfAbsent)
The Cache2K version returns a boolean. What does that mean and what does this tell me when more than 1 thread inserts a value using the same key.
Any help would be greatly appreciated as I am a bit unsure on how to deal with this. I am using the latest version 0.26-BETA.
Thanks and best regards,
Michael
putIfAbsent() is equivalent to:
if (!cache.containsKey(key)) {
cache.put(key, value);
return true;
} else {
return false;
}
except that it is executed atomically.
The method returns true, if the value was inserted (that implies it was not existing before). Since it is executed atomically, only the thread, which value was successfully inserted, gets the true value.
Mind that put may invoke a writer, if registered. The writer is not invoked, if the value is already present.
The semantic of this method is identical to JCache/JSR107. This behavior might not make sense for all situations or is intuitive. See a discussion in https://github.com/jsr107/jsr107spec/issues/303.
If you like, please try to explain in another question about your use case or you desired cache semantics, so we can discuss what the best approach might be.

Capture a return value for logging and then return the value in Scala

What is the most 'scala-ic' way to capture a value (possibly one that is not idempotent) for logging and returning the same value.
I can think of 'return' statement the only way to do it, but apparently using 'return' should be avoided in scala .
Use case:
def myfunc(argument) : ReturnType{
val response:ReturnType = dependency()
// dependency() is not idemptotent
// so calling more than once will have side-effects
logger.debug(response.member1 , response.member2)
return response
}
Is there a way to achieve this without using a 'return' keyword.
I am a newbie to scala so some (or most) of what I said could be wrong, and would be happy to be corrected.
Just reifying #Shadowlands answer.
def myfunc(argument: ArgType): ReturnType {
val response = dependency()
logger.debug(response.member1, response.member2)
response
}