What should be expected value when using 2 different threads? - java

I was given a question in class saying 'What are the possible final values of a? (Assume that each statement is a unit of execution. You do not need to consider the problem at the instruction level.)'. With additional information:
Thread A: a = 3 (A1) and a = a + 1 (A2)
Thread B: a = 5 (B1) and a = a + 7 (B2)
So after some thought that First thread output should be 4 and second threads output should be 12.
So I did the test script to see if that's correct and output shows what I expected Thread A: 4 and Thread B: 12.
The question is, should I expect other values? Or maybe I'm just implementing this question wrong? How I can tweak this code to get other values, if possible? Is that a tricky question, or its just me?
EDIT: Since code was not really needed for my homework assignment, lets focus on theoretical implementation of such problem.

Assuming you do fix your code to correctly implement threading, given today's CPU speeds and the overhead of starting threads/scheduling I bet you won't see any concurrency bugs, because either the first thread or the second one will finish their update of a before the other one has a chance to start, so you'll probably always get 4 and 12 as results.
You'll need much more lengthy tasks for a data-race to occur.

If you ever correct this so it really exhibits threading rather than sequential execution, the correct answer would be that in the absence of any kind of synchronization the behaviour is undefined.

Your calls to FirstThread and SecondThread are running on the main thread, not threadA or threadB. Also, the run() method does nothing.
Any references to threading in this problem are merely misdirection (noise) and have nothing to do with the output.
(Also the method names FirstThread and SecondThread should start with a lowercase letter to match Java convention)

If I understand your question correctly, the code you give was not given as part of the homework question but rather represents you attempt to answer it. Given that, as Tudor already points out even in a correct implementation you might not see any "surprising" values, even if you run the program a few hundred times. Concurrency bugs are hard to find by testing.
My hint for understanding the correct answer is the following:
Consider you are cooking two dishes for dinner with your loved one. You can cook the (spicy) main dish first and the (sweet) desert afterwards. (No threading). Or you cook them at the same time, switching between the two recipes. Both of them might refer to a pan (initially filled with air), one tells you to replace the content of your pan with eggs, the other to replace the content with oil and then add spices. Because you are a bad cook (you didn't learn about synchronization yet) you start by putting in oil, then replace everything in it by eggs, add sugar and then return to the first recipe and add spices ... what will it taste like?

You can get other values but you need to do something to make the program do because something with thread is random and it's hard to control.you can try my code i think there's something wrong in your code, but i don't change it, ok?
public class Threads implements Runnable
{
int a = 0;
public void run() { }
public int FirstThread()
{
a = 3;
Thread.sleep(2000);
a = a + 1;
return a;
}
public int SecondThread()
{
a = 5;
a = a + 7;
return a;
}
}
or use this one
public class Threads implements Runnable
{
int a = 0;
public void run() { }
public int FirstThread()
{
a = 3;
a = a + 1;
return a;
}
public int SecondThread()
{
a = 5;
Thread.sleep(2000);
a = a + 7;
return a;
}
}
just try it!!!

Related

Unable to return a variable [duplicate]

I'm trying to understand the difference, and benefits of using System.out.println() vs. return blah in a method.
It seems like System.out.println() is used to display static information, and return is a value returned from the method. Yet I'm seeing examples like the one below, where a function is used within the System.out.println() statement
System.out.println(name.substring(1, 3));
When is it right to use System.out.println() and return. Is it that return can be used by another piece of code later, whereas System.out.println() cannot?
Your last sentence is effectively correct, but the distinction between these two operations is HUGE, so I'd like to provide a more in depth explanation of their differences.
The Difference:
return is an instruction that controls the flow of your program's execution. It is a fundamental part of the Java syntax. It tells the computer what part of your code to execute, and what values to use during that execution. When you return a value, you are saying "The result of calling this method is XXXX" (with 'XXXX' being the value you returned).
System.out.println is not used to control how your program executes. It is a merely way to inform the user of what is going on inside your program. System.out.println (syso for short) can print any information to the console; it doesn't matter if it's a variable, an expression, or the result of a method call. There is no limitation to "static" data.
Let's look at both of them in action:
int addInts(int arg0, int arg1)
{
return arg0 + arg1;
}
This means that wen we call addInts in our program, it will evaluate to the sum of its arguments. So when we write addInts(3, 7), it's the same as if had simply written 3 + 7 or 10 in our source code. Nothing is printed to the console; all we've done is give our program a way of calculating something.
However, any calculations we might make are ultimately useless if all they do is sit inside the computer, so we need a way to display this information to the user. Enter syso:
System.out.println(addInts(22, 16));
The addInts method is called and returns 38. This value is placed somewhere in the computer's memory such that our program can find it.
Next, syso takes that value (38) and prints it to the console, letting the user know what value was calculated. Nothing new is calculated from this procedure, and our program continues to the next statement.
So which do I use?
In simple programs, you have so few values to keep track of that it can be tempting to just print everything that you want to know where you calculate it. For instance, if you were writing a program to do your algebra homework (I've been there) and you wrote a method to solve the quadratic equation, it might be tempting to structure it like this:
class Algebra
{
static void quadSolve(double a, double b, double c)
{
double result = /* do math... we're ignoring the negative result here*/;
System.out.println("The solution to the quadratic equation is: " + result);
}
public static void main(String[] args)
{
quadSolve(1.0, -6.0, 9.0);
}
}
However, this approach quickly becomes a very bad idea if you want to make your program a little more complex. Let's say one problem requires you to solve the quadratic equation and then use the result of that calculation to calculate the volume of a cylinder. In the above example, we can't do that: after we dump the value of result to the console via syso, it disappears when the quadSolve method ends. It would make much more sense if we have quadSolve return result and let the "caller" (the place quadSolve was called from) deal with handling that value. This is a much more flexible design that allows us to make our programs much more complicated with relative ease. This increased flexibility and modularity is really what makes methods useful. Here is the implementation:
class Algebra
{
static double quadSolve(double a, double b, double c)
{
double result = /* do math... we're ignoring the negative result here*/;
return result;
}
public static void main(String[] args)
{
double x = quadSolve(1.0, -6.0, 9.0);
//now we can do whatever we want with result:
//print it, negate it, pass it to another method-- whatever.
System.out.println("The solution to the quadratic equation is: " + x);
System.out.println("And it's square is: " + (x * x));
}
}
I hope this clears things up. Feel free to ask if you need additional clarification.
A method often returns a value (which is done by using the return statement).
Information may be "printed" to an output stream by System.out.println() references.
They both have their uses ... which are usually orthogonal.
They have very little to do with each other.
System.out.println() is used to output strings to a console/terminal. So
System.out.println("Hello world");
should output the string "Hello world"
return is a statement in Java to go back to the code that invoked the method and pass back a value.
public static int add(int a, int b) {
return a + b; // go back to method that called this method (main)
}
public static void main(String[] args) {
int sum = add(3,4); // the return result (7) is stored in sum
}
From my understanding, and to give a simple answer which has a significant meaning, I would say:
It is like when you go to a coffee shop and order a cup of coffee, but the barista tells you if you want a picture of the coffee cup or the cup itself :).
System.out.println() is the picture, while..
return blah is the cup of coffee.
With "return" you can do what you like with the value of return, but with "print" you only see what the function is doing.

execution of task in java within specified time

I want to execute few lines of code with 5ms in Java. Below is the snippet of my code:
public void delay(ArrayList<Double> delay_array, int counter_main) {
long start=System.currentTimeMillis();
ArrayList<Double> delay5msecs=new ArrayList<Double>();
int index1=0, i1=0;
while(System.currentTimeMillis() - start <= 5)
{
delay5msecs.add(i1,null);
//System.out.println("time");
i1++;
}
for(int i=0;i<counter_main-1;i++) {
if(delay5msecs.get(i)!=null) {
double x1=delay_array.get(i-index1);
delay5msecs.add(i,x1);
//System.out.println(i);
} else {
index1++;
System.out.println("index is :"+index1);
}
}
}
Now the problem is that the entire array is getting filled with null values and I am getting some exceptions related to index as well. Basically, I want to fill my array list with 0 till 5ms and post that fill the data from another array list in it. I've not done coding since a long time. Appreciate your help.
Thank You.
System.currentTimeMillis() will probably not have the resolution you need for 5ms. The granularity on Windows may not be better than 15ms anyway, so your code will be very platform sensitive, and may actually not do what you want.
The resolution you need might be doable with System.nanoTime() but, again, there are platform limitations you might have to research. I recall that you can't just scale the value you get and have it work everywhere.
If you can guarantee no other threads running this code, then I suppose a naive loop and fill will work, without having to implement a worker thread that waits for the filler thread to finish.
You should try to use the Collection utilities and for-each loops instead of doing all this index math in the second part.
I suppose I should also warn you that nothing in a regular JVM is guaranteed to be real-time. So if you need a hard, dependable, reproducible 5ms you might be out of luck.

Why don't threads run consistently?

I am playing around with multithreading and came across an inconsistency when running a small snippet of code. The following code should print out 123123... but what I'm getting is
class RunnableDemo implements Runnable {
private String message;
RunnableDemo(String m) {
message = m;
}
public void run() {
try {
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestThread {
public static void main(String args[]) throws InterruptedException {
new Thread(new RunnableDemo("1111111")).start();
new Thread(new RunnableDemo("2222222")).start();
new Thread(new RunnableDemo("3333333")).start();
}
}
Output: 123231231132123231321
Output: 123213123123213213213
Output: 123231213213231231213
What I don't get is that it run correctly the first pass through (prints '123') but then the second pass through it prints '231'. If the thread is printing a char, sleeping 1 second, then repeating. Shouldn't the pattern 123123... be consistent each time I run the code or at least follow the pattern of the first 3 chars?
The following code should print out 123123
Not necessarily. You should basically never rely on threads with no synchronization between them happening to wake up and execute in any particular order.
Let's take the very first character output: there's no guarantee that that will be 1. Yes, you're starting the thread printing 1 first, but that doesn't mean that's the first thread that will actually start executing run first - or even if it does, that doesn't mean that's the first thread that will get as far as the System.out.print call.
Given the fairly long sleep, I would expect (but ideally not rely on) the output being a sequence of 7 "chunks", where each "chunk" consists of the characters "123" in some permutation. But if you've got three threads which all go to sleep for a second at "roughly" the same time, you shouldn't expect them to necessarily wake up in the order 1, 2, 3 - and again, even if they do, one of them may pre-empt another within the loop body.
On a really, really slow machine, even that expectation would be invalid - imagine it takes a random amount of time between 0 and 20 seconds to call charAt - unlikely, but it's a feasible thought experiment. At that point, one of the threads could race ahead and finish its output before another of the threads managed to print anything.
Threads are designed to be independent - if you want them to work in a coordinated fashion, you have to specify that coordination yourself. There are plenty of tools for the job, but don't expect it to happen magically.
You can't predict what piece of program CPU runs at a time. While running some process the CPU converts the process into small pieces of work. As multiple processes are running at a time. CPU has to schedule according to scheduling algorithm implemented. So, in short, you cannot predict what CPU does next unless you programmatically synchronize the pieces of code.

thread skips some iterations

I wrote a method that should be repeated 1000 times and the method is again another loop (like a nested loop).Since the running time was not reasonable I decided to write a thread to run it faster. Here is the method:
public class NewClass implements Runnable {
#Override
public void run() {
for (int j = 0; j < 50; j++) {
System.out.println(i+","+j);
/*
*
* my method
*/
}
}
}
and here is the way the main class calls it:
for (int i = 0; i < 1000; i++) {
NewClass myMethod = new NewClass();
Thread thread = new Thread(myMethod);
thread.start();
}
the problem is that when I run it, the thread skips the first iteration (when i=0) in the main class and then in the next iterations, it skips some iterations of inner loop (myMethod). Here is the result of println:
1,0
1,1
2,0
2,1
3,0
3,1
3,2
...
3,22
4,0
...
clearly it skips i=0 and for other iterations it cannot finish it. I'm sure the problem is not in the body of method. I run it several times without thread. It is the first time I write thread and I think the problem is in thread.
Your loop index for i starts from 1 (I'm guessing? It's not even clear why it's in scope), so it's unsurprising that i = 0 does not occur. Similarly, I think you're confused about the printing order, which need not be deterministic. It may be printing the output interspersed with output from other threads. This is normal and expected. I think the code is behaving correctly, it might just not be doing what you want.
I noticed you edited your code. This doesn't really bode well for anybody being able to help you diagnose whatever unexpected behavior you're seeing.
It just so happens that no thread calls the print function while i is zero. You don't compel this ordering, so it may or may not happen in that order. Either of these things can happen.
i is zero
A thread is created.
The thread prints the value of i.
i is incremented.
Or
i is zero
A thread is created.
i is incremented.
The thread prints the value of i.
Your code doesn't enforce either ordering, so it can happen either way. You only have guaranteed ordering between threads when something in your code guarantees such ordering.
clearly it skips i=0 and for other iterations it cannot finish it. I'm sure the problem is not in the body of method. I run it several times without thread. It is the first time I write thread and I think the problem is in thread.
There are 2 reason why this could be happeneing.
You seem to be printing out i which is a shared between threads without any memory synchronization. See the tutorial on memory synchronization. Each processor has internal cached memory so even though i is being modified in the main memory, the processor cache may still see the old value.
You also are probably seeing a race condition. What is happening is that the first two threads (0 and 1) are started before either of their run() methods actually being called. So when they both run and print out 1 because that is what i's value is at the time.
Because of either or both of these reasons, if you run your application 10 times you should see vastly different output.
If you want i to be shared then you could turn it into an AtomicInteger and do something like:
final AtomicInteger i = new AtomicInteger(0);
...
// replacement for your for loop
i.set(0);
while (true) {
if (i.incrementAndGet() >= 1000 {
break;
}
...
}
...
// inside the thread you would print
System.out.println(i + "," + j);
But this mechanism does not solve the race condition. Even better would be to pass in the i value to the NewClass constructor:
private int i;
public NetClass(int i) {
this.i = i;
}
...
Then when you create the instances you do:
NewClass myMethod = new NewClass(i);

fizzbuzz - can it be shorter?

WARNING:I'm not asking for a better code, I'm asking for a shorter code for HackerRank just to learn what can be done to shorten it.
I'm newbie to Java and was trying out this FizzBuzz problem:
Write a program that prints the numbers from 1 to 100. But for multiples of three print >“Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which >are multiples of both three and five print “FizzBuzz”.
I wrote my solution as short as possible.
class Solution{
public static void main(String[]b){
for(int i=1;i<101;i++){
String a=(i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i+"";
System.out.println(a);}}}
and I got a 3.6 score. But obviously there's room to improve because some people wrote it with 27 characters less. How is that possible ? Any suggestions? I don't really care about the ranks, I just wanna know what I'm missing.
EDIT: So with your help, I made it like this:
class Solution{public static void main(String[]b){for(int i=1;i<101;i++){System.out.println((i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i);}}}
and it seems I got rid of 14 characters. God knows what the other people did to lose 13 more characters. Anyway, thanks.
What about something like:
for(int i=0;i++<100;System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz")))
Warning: this code is just an exercise of trying to make the code shorter. It is neither good or readable as normal code should try to be!
Yes, it is possible to make it even shorter. Proof: According to the leaderboard, the highest score for java is 7.00.
How? Spoiler: identifier(s), parentheses, line breaks, pre/post increment. The conditions may be written as i%3>0 or the opposite like i%3<1.
class S{public static void main(String[]a){for(int i=0;++i<101;)System.out.println(i%3>0?i%5>0?i:"Buzz":"Fizz"+(i%5>0?"":"Buzz"));}}
It may not be getting significantly shorter yet, most likely due to the boilerplate code for main and print method. Based on everything suggested on this QA so far, it is possible to achieve at least 6.90 in Java if not the current max which is 7.00.
For example,
class S{public static void main(String[]a){for(int i=0;++i<101;)System.out.println(i%3>0?i%5>0?i:"Buzz":i%5>0?"Fizz":"FizzBuzz");}}
If we are open to try out other languages, we may wish to try JS with caution/advisory.
Many more approaches have been discussed here and here.
Java, C, C++, C#, Python, Ruby, R, none of the submissions in these languages reached the top score yet which is 16.0. It leads us to the question, which submission led to the top score? The answer is bash scripting. Proof: leaderboard for bash
How? The hint has been kindly provided by the author of the top submission, Byron Formwalt at here.
If we are new to bash scripting, we may wish to get started with few resources mentioned here, here, and here.
Disclaimer: Even though this may be suitable for the purpose of the getting higher score in hackerrank or just for exercise, it may not be a good practice for Best_coding_practices. There are many scopes for improvement in this post. Suggestions are welcome. Acknowledgements/Thanks.
It just becomes an argument to migrate to Kotlin!
fun fizzBuzz(number: Int) = when {
number.divisibleBy(3) and number.divisibleBy(5) -> "Fizz-Buzz"
number.divisibleBy(3) -> "Fizz"
number.divisibleBy(5) -> "Buzz"
else -> number.toString()
}
fun Int.divisibleBy(number: Int) = this % number == 0
fun main() {
(1..100).forEach {
println(fizzBuzz(it))
}
}
function fizzBuzz(n) {
for (i = 1; i <= n; i++) {
let result = "";
if (i % 3 === 0) result += "Fizz";
if (i % 5 === 0) result += "Buzz";
if (i % 7 === 0) result += "Foo";
console.log(result || i);
}
}
fizzBuzz(105);
It will check every condition, if all are true then all will be added together as well as it works with the single true condition as well as two true conditions.

Categories