Will Java asyncronously call these methods automatically? - java

Let's say I call a method like this:
myBigMethod(
getMethodParam1(arg1, arg2),
getMethodParam2(arg2, arg3),
getMethodParam3(arg3, arg4)
);
Will calls to getMethodParam1, getMethodParam2 and getMethodParam3 be called asynchronously by Java or not?

Java will never do anything asynchronously if you don't tell it to do so.
And assuming that there is a method like myBigMethod(a, b, c) it is going to evaluate each parameter first before it can pass the result to the method. From left to right.
So your example is equivalent to:
a = getMethodParam1(arg1, arg2);
b = getMethodParam2(arg2, arg3);
c = getMethodParam2(arg3, arg4);
myBigMethod(a, b, c);

No, JVM will call getMethodParam's methods one by one. If you want call these methods in parallel you shoud do it by yourself

If you are implying something like Haskell's non-strict evaluation semantics, then rest assured that Java, just like any other major programming language, has strict semantics and arguments are passed by value only, which means that the values must be calculated first.
If your question is possibly about whether Java guarantees order of argument evaluation, then the answer is Yes, the expressions will always be evaluated from left to right.

Java will evaluate the arguments before the method is called. So in your case, getMethodParam1/2/3 will be evaluated before myBigMethod is called.

First of all you can simply check it with a test and a big for loop. Or even debug, you'll see that methods are called one by one.
Think yourself, it could be very dangerous if JVM make such decisions by itself.

Related

Is Java lazy when passing parameters to a method?

I am using this code:
A a = aMap.contains(key) ? aMap.get(key) : createAExpensively(key);
I believe that Java is lazy so if aMap.contains(key)) then the createAExpensively() function is never called.
Then, I stumbled onto the Map.getOrDefault() method. If we instead use:
A a = aMap.getOrDefault(key, createAExpensively(key));
is Java still lazy in calling the createAExpensively() function?
It seems that Java will first create the object A and pass it as a method parameter, based on this question, but I'm not totally sure.
If Java is not lazy when using Map.getOrDefault(), what is the point of that method?
Is Java still lazy in calling the createAExpensively() function?
[in .getOrDefault(key, createAExpensively(key))]
Function parameters are evaluated (from left to right) before actually calling the function. So createAExpensively(key) will be evaluated before calling getOrDefault. This behavior is also known as applicative order evaluation strategy.
If Java is not lazy when using Map.getOrDefault(), what is the point of that method?
It's useful when the default value is not expensive to create,
for example when it's an already computed value or constant.
In that case the Map.getOrDefault(...) call allows a more compact syntax than the ternary operator.
If the default value is expensive to compute,
and if you actually want to put the computed value in the map,
then as of Java 8,
you can use computeIfAbsent:
A a = aMap.computeIfAbsent(key, k -> createAExpensively(k));
Java is not lazy at all. You are using conditional operator to check whether aMap.contains(key). If this is true it will never call createAExpensively(key) but aMap.get(key)
It isn't lazy in that case.
The point of the method is that there's lots of times when the default is a constant or something you've already computed anyway. For example, you might use getOrDefault(key, 0) when you're getting some kind of count and absent keys should be counted as zeroes.
This is called "short-circuit evaluation" rather than lazy evaluation: The JVM is not deferring evaluation of createExpensively(), but rather avoiding it completely if it's not necessary, i.e if the condition holds.
See also the answer to the following question here on StackOverflow:
Java logical operator short-circuiting
It is not lazy at all.
This code
A a = aMap.contains(key) ? aMap.get(key) : createAExpensively(key);
evaulates to
if (aMap.contains(key))
{
a = aMap.get(key);
}
else
{
a = createAExpensively(key);
}

ThreadLocal plus-equals (+=) in Java?

Programming noob here, so probably a dumb question, but there is no plus-equals (+=) operator for a ThreadLocal variable in Java, is there? This sort of thing works fine:
public static ThreadLocal<Double> tl = new ThreadLocal<>();
public double whatever;
//stuff here
double temp = tl.get()+whatever;
tl.set(temp);
Or replacing the last two lines with:
tl.set(tl.get()+whatever);
Just wanted to make sure there was no other way. It'd be nice if there were something like:
tl.add(whatever);
ThreadLocal can contain and work with object of any provided type, so method "add" just is not "generic" enough. You can set your object, you can get your object, and having reference to it you can do whatever you need, but it is out of ThreadLocal responsibility.
The reason you cannot perform the += operation is because in Java, primitives are passed as value not reference. What ends up happening when you call .get() is it returns a copy of the value being held not a pointer to the actual value. So changing the returned value will have no effect.
You will need to utilize the .set(tl.get()+x) idiom that you describe.
There is no operator overloading in Java. You can not do that. In the other hand in a language like C++ you could do it.
In deed, there is no add-method in class ThreadLocal. Look here.

Calling Level of method

In object oriented based programming language like java we can call a method of object by using objectName.methodName() -
aStudent.getName().equals(anotherStudent.getName());
Here to achieve the equals() method I have to use two dots (.). In some case there might be more than 2 dots like -
objectName.methodName1().methodName2().methodName3().methodName4()
My question is - Is there any limitation of such level of method calling ?
There is no technical limit, since writing:
result = foo.bar().baz();
is equivalent to writing
bar = foo.bar();
result = bar.baz();
There is, however, often a design limit: if you are accessing the child of a child of a child of ... an object, you might be violating the Law of Demeter (and this article might clear things up further, in case you're interested.)
As long as the method return an object, you can call any public method of this object, so no there is no limitation (none that you should matter.. there is always a limit).
Note that the approach may have no limit, but is not recommended at all, as it is harder to read, and harder to validate in one of the object is null.

Most efficient way to pass a Java object around?

I'm considering creating the following method:
public static MyBigCollection doSomeStuff(MyBigCollection m) { ... return m; }
and then in another method (perhaps in another class), using it like so:
MyBigCollection mbc = new MyBigCollection();
mbc = stuffClass.doSomeStuff(mbc);
Am I going about this the right way -- is this an efficient way to "do some stuff" to an object? I'd like to break off the stuff like so for extensibility. I've been doing c# for so long I'm just not sure with java. In c# the method could return void and I can simply call doSomeStuff(mbc) -- which would effectively pass my object by reference and do some stuff to it. I've been reading that java works differently so I wanted to check with the experts here.
I'd refactor to:
stuffClass.doSomeStuff(mbc);
(i.e., a method that modifies mbc and returns void)
Keep in mind that all Java Objects are stored in heap memory, and passed around with reference pointers.
The way you're doing it is fine, but you don't actually need to return the object at the end of the method. As such, the following would be simpler...
MyBigCollection mbc = new MyBigCollection();
stuffClass.doSomeStuff(mbc);
Objects in Java are passed by reference, so any modification on the mbc Object in the doSomeStuff() method would still be retained in the mbc variable after the end of the method call.
The only reason why you might consider returning the mbc Object is if you want the ability to join multiple methods together, such as this...
MyBigCollection mbc = new MyBigCollection();
mbc.doStuff1().doStuff2().doStuff3();
In this case, because mbc is returned by each of the doStuff() methods, the next method can be called straight back on to the same Object. Without returning the reference, you'd have to do something like this instead...
MyBigCollection mbc = new MyBigCollection();
mbc.doStuff1();
mbc.doStuff2();
mbc.doStuff3();
Which is the same thing, but not quite as compact. How you go about it really depends on how you intend to use the methods and the Object itself.
There's only one way to pass Java objects around. Java passes everything by value. Objects aren't passed; they live on the heap. You pass references around, not objects.
Same as C#, as far as I know.
This kind of micro-optimization is usually meaningless.
I think your question is around how Java passes references to objects. Java passes by value, which can be confusing when first said. For objects, this means that the value of the reference to the object is passed to the method. Interacting with the object referred to by the value will alter the object 'passed in', so you don't need to return it.
Strings are treated differently as they are immutable. Primitives are also pass by value, but as the value passed is not a reference, you will not alter the original variable.
The easiest way to test this is to write some code and observe (you might also consider the Java tutorials)

Performance: calling a method recursively vs. using conditional logic

I call a method with a variable x, I make some checks and if some conditions are true I have to execute part of the same method with a different variable value.
What is more effective?
to call the method again (recursion), or
to change the value of my variable and leave the program to execute the following lines of the method?
In both cases i can make it work but what is the more efficient way?
For the second case, I use an if statement on top. I read the value I want and then the following if statements are executed using this value.
public void mymethod(x){
if (con){
x = something;
}
if (con2){
//do something
} else if(con3) {
//do something
}
}
As Dave said, you probably should not be concerned at all about such micro-optimizations. The best thing to do is to write your code in such a way that it is easiest to read and understand. The best approach in my opinion would be to move the "do something" part into a separate function, and pass to it all the parameters that it needs in order to do its job.
If you really want to get down to efficiency talk, be advised that modern systems tend to rely heavily on caching, so many approaches to performance which used to work in the past do not actually constitute improvements anymore. On the contrary, they worsen things.
it is more efficient to modify the value of x and continue the method execution. The reason is simple. When you call a function, the caller state must be saved (into a stack) then local variables of the called method are read and so the called method is executed. So, being already in the called method myMethod it'd be "cheaper" to access the variable x to modify its value and then continue

Categories