The code below works fine, however I want value to reach the end of the array, as at the moment it start from 1 then goes to the end of the array.
Booth[] boot = new Booth[numberOfBooths];
for (int j = 1; j < boot.length; j++) {
boot[j] = new Booth(j, buff);
boot[j].start();
}
for (int j =1 ; j < boot.length; j++) {
try {
boot[j].join();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
I altered the code so the loops start from 0.. such:
for (int j = 0; j < boot.length; j++) {
boot[j] = new Booth(j, buff);
boot[j].start();
}
for (int j =0 ; j < boot.length; j++) {
try {
boot[j].join();
} catch (InterruptedException ex) {
System.out.println(ex);
}
But after debugging as soon as it gets to the join the program stops. I read about Deadlock and maybe that was the reason for this, could there be a way around it, is there a general solution to this problem?
Edit: Sorry I haven't been so clear. The code works either way, however when I run it a second time ( I have my program in a while loop ) it doesn't do the join
It sounds as if the thread pointed to by boot[1] completes, but the thread pointed to by boot[0] does not.
Therefore something about new Booth(0,buff) creates an object for which run() doesn't terminate.
Try unit testing Booth without using threads, and just run:
Booth b = new Booth(0,buff); // initialise buff first, of course
b.run();
... and see whether this returns. If not, work out why, perhaps by stepping through it with a debugger.
The other thing to look out for is deadlock around the shared buff object. Unless there is some locking around buff, you can certainly expect issues. However that seems less likely if starting your index at 1 solves the problem.
If the whole thing works the first time around, but not on a second attempt, then you should consider the state of buff. Perhaps new Booth(0,buff).run() is non-terminating when supplied a certain state of buff.
Aside: It's cleaner to not do class Booth extends Thread but instead class Booth implements Runnable.
Then instead of Booth.start() use
Thread t = new Thread(booth);
t.start();
That way you're not polluting the Booth code with the knowledge that it's going to be a thread -- it's better encapsulation.
Related
I miss thought about the stop condition of a loop, and therefore the program didn't stop raising CPU to its limits.
The whole Intellij process hangs and become totally unresponsive, knowing that my machine disposes i7 and I am running on Ubuntu which is normally multitasking as any modern OS. I imagine a solution like pausing a program if it continues executing without a change of state, after a time threshold or just when the memory state stagnates (many ideas can be thought).
Is there an established programming solution to stay safe from one of these situations (when testing, I am aware that an infinite program can be useful) but in case infinitely doing basic CPU operation, it is not.
Does running inside a differed thread help CPU charge dispatching resources ?
Is there a way in Intellij to stay safe from such a situation.
int rect_a = 100;
int rect_b = 50;
for (int j=1; j<rect_a; j++) {
for (int i=0; i<j; i++) {
//some computation
j = method() that returns 0 alwayse. (bad logic)
}
}
As your code is reset j to zero then the code will never end
consider
int rect_a = 100;
for (int j=1; j<rect_a; j++) {
for (int i=0; i<j; i++) {
j = 0;
}
}
System.out.println("ended");
ended is never printed. The computer is only doing what you tell it to
This is my homework problem:
I have to do matrix multiplication. My code should create a thread to each element in the resultant matrix. i.e., if resultant matrix is mXn size then there should be m*n threads.
(http://iit.qau.edu.pk/books/OS_8th_Edition.pdf page 179)
Yes I finished it by my own. Which is executing fine with all my test cases. Unfortunately, I end up getting 70% credit :(
This is my code and test cases.
Matrix Multiplication.zip
When I met my professor regarding my marks. He told me that my code taking too long to execute larger size matrix.
I argued with him that it is a expected behavior as it is obvious that large size data takes more time. However, he disagree with me.
I attached my code and test cases . My code is taking 3 hours. As per my professor it should only take 5 min to execute.
I tried to figured out for last couple of days but I couldn't find exact solution :(
outline of my code
ExecutorService executor = Executors
.newFixedThreadPool(threadCount); // creating thread pool
// with fixed threads
int mRRowLen = matrix1.length; // m result rows length
int mRColLen = matrix2[0].length; // m result columns length
mResult = new long[mRRowLen][mRColLen];
for (int i = 0; i < mRRowLen; i++) { // rows from m1
for (int j = 0; j < mRColLen; j++) { // columns from m2
Runnable r = new MatrixMultipliactionThread(matrix1ColLen, i, j, matrix1,
matrix2);
executor.execute(r);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
// wait untill it get shutdown
}
Run method :
public void run() {
for (int k = 0; k < m1ColLength; k++) { // columns from m1
Matrix.mResult[i][j] += matrix1[i][k] * matrix2[k][j];
}
Thanks in Advance
Ok, I downloaded your zip and ran the program. Your problem isn't in the matrix multiplication at all. The advice in the comments is still valid about reducing the number of threads, however as it stands the multiplication happens very quickly.
The actual problem is in your writeToAFile method - all the single-threaded CPU utilization you are seeing is actually happening in there, after the multiplication is already complete.
The way you're appending your strings:
fileOutputString = fileOutputString + resultMatrix[i][j]
creates thousands of new String objects which then immediately become garbage; this is very inefficient. You should be using a StringBuilder instead, something like this:
StringBuilder sb=new StringBuilder();
for (int i = 0; i < resultMatrix.length; i++) {
for (int j = 0; j < resultMatrix[i].length; j++) {
sb.append(resultMatrix[i][j]);
if (j != resultMatrix[i].length - 1) sb.append(",");
}
sb.append("\n");
}
String fileOutputString=sb.toString();
That code executes in a fraction of a second.
I have 8 threads which each execute loops similar to this in their run method:
for (int i = 0; i < someVar; i++) {
for (int j = 0; j < someOtherVar; j++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
// another loop and some calculations here
}
}
I start the Threads like this:
executor = Executors.newFixedThreadPool(threads);
// generate the threads and run them
for (int i = 0; i < threads; i++) {
MyClass cls = new MyClass(i);
executor.execute(cls);
}
Now I need to be able to pretty much instantly kill my threads, that's why I added the if statement above and use at another point executor.shutdownNow(). But it just isn't working fast enough. Some calculations might take a few seconds before they finish and the next iteration starts.
Is there any other reliable way to pretty much immediately shutdown threads?
You need an interrupt operation that calls into the thread and stops the current execution. Here's some documentation: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
I wrote a simple code that uses multiple threads to calculate number of primes from 1 to N.
public static void main (String[] args) throws InterruptedException
{
Date start;
start = new Date();
long startms = start.getTime();
int number_primes = 0, number_threads =0;
number_primes = Integer.parseInt(args[0]);
number_threads = Integer.parseInt(args[1]);
MakeThread[] mt = new MakeThread[number_threads];
for(int i=1;i<=number_threads;i++)
{
mt[i-1] = new MakeThread(i,(i-1)*(number_primes/number_threads),i*(number_primes/number_threads));
mt[i-1].start();
}
for(int i=1;i<number_threads;i++)
{
mt[i-1].join();
}
Date end = new Date();
long endms = end.getTime();
System.out.println("Time taken = "+(endms-startms));
}
}
As show in above, I want the final time taken to be displayed (just to measure performance for different inputs). However I noticed that when I enter a really big value of N and assign only 1 or 2 threads, the scheduler seems to override the join functionality (i.e the last print statement is displayed before other threads end). Is the kernel allowed to do this? Or do I have some bug in my code?
P.S: I have only shown a part of my code. I have a similar System.out.println at the end of the function that the newly forked threads call.
Your loop is the problem.
for(int i=1;i<number_threads;i++)
{
mt[i-1].join();
}
Either you change the condition to <= or you make a less cryptic loop like this:
for(int i=0; i < number_threads;i++){
mt[i].join();
}
Or a for each loop:
for(MakeThread thread : mt)
thread.join();
Provided you correct your loop which calls join on all threads as shown below
for(int i=0;i<number_threads;i++)
{
mt[i].join();
}
there is no way that the last print line may get invoked before all threads ( as specified in the loop ) finish running and join the main thread. Scheduler cannot make any assumptions with this semantics. As pointed by Thomas , the bug is there in your code that does not call join on the last thread ( which therefore does not complete before the last print is called ).
I saw this bit of code on the interents somewhere. I'm wondering what the do is for.
public class LoopControl {
public static void main(String[] args) {
int count = 0;
do {
if (count % 2 == 0) {
for (int j = 0; j < count; j++) {
System.out.print(j+1);
if (j < count-1) {
System.out.print(", ");
}
}
System.out.println();
}
count++;
}
while (count <= 5);
}
}
By which I mean what exactly does do mean? What's its function? Any other information would be useful, too.
It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.
Sun tutorial on while and do-while.
Oh, and in this case it will print:
1, 2
1, 2, 3, 4
Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.
It is similar to a while loop, with the only difference being that it is executed at least once.
Why? Because the while condition is only evaluated after the do block.
Why is it useful? Consider, for example, a game menu. First, you want to show the menu (the do block), and then, you want to keep showing the menu until someone chooses the exit option, which would be the while stop condition.
It's a while loop that gets executed at least once.
Edit: The while and do-while Statements
do { ... } while(CONDITION) ensures that the block inside do will be executed at least once even if the condition is not satisfied, on the other hand a while statment will never execute if the condition is not met
It goes with the while. do { ... } while() is a loop that has the conditon in the end.