Currently I'm trying to implement a prime finder using threads in java. Unfortunately it does not seem to work the way I intend it to.
What I basically want is that I have a while(true) loop to generate numbers indefinitely. After a number is generated,a thread should grab that number and check if it is a prime number. While the first thread is still checking for prime, the second thread already grabbed the next number to check for prime and so on.
Right now the number generating does work but all threads seem to use the same number, which makes no sense for my implementation.
This is the current state of my project:
public class Main {
public static void main(String[] args) {
int logicalCores = Runtime.getRuntime().availableProcessors();
int startFrom = 0;
startCalc(logicalCores, startFrom);
}
public static void startCalc(int threadCount, int startFrom){
for (int i = 0; i < threadCount; i++ ){
PrimeCalculator calculator = new PrimeCalculator(startFrom, i);
Thread thread = new Thread(calculator);
thread.start();
}
}
}
import static java.lang.Thread.sleep;
public class PrimeCalculator implements Runnable{
int startingCounter;
int id;
public PrimeCalculator(int counter, int id){
this.startingCounter = counter;
this.id = id;
}
#Override
public void run() {
Integer counter = startingCounter;
while(true){
if (isPrime((counter))){
System.out.printf("Thread with ID %d found that %d is a prime! \n", id, counter );
try{
sleep(10000);
} catch (Exception e){
}
}
synchronized (counter){
counter++;
}
}
}
public static boolean isPrime(int n)
{
if (n == 2 || n == 3 || n == 5) return true;
if (n <= 1 || (n&1) == 0) return false;
for (int i = 3; i*i <= n; i += 2)
if (n % i == 0) return false;
return true;
}
}
The problem is that all threads seem to keep checking the same number. E.g the number is 2, but all 16 Threads of my CPU check for prime while in reality a thread like Thread0 should check the number 2 for prime while others are already checking an increment of the counter (e.g Thread15 is already at 16) etc.
EDIT:
I think I need to give a better example of the expected behaviour.
Let's say I have a computer with 4 cores and 4 threads. This would make the logicalCores variable in my main method 4 and create 4 threads in the function "startCalc".
Now a loop should generate numbers from a defined starting point. Let's just say that point is 0.
What should happen now is that a thread, let's just call it thread0 is taking that number and checks if it is a prime. In the meantime the loop generated an increment of the counter and sits at "1" now. Now, because thread0 is still checking if 0 is a prime, a second thread, thread1, grabbed the current counter with the value "1" and is checking if "1" is a prime.
The goal here is that each thread is checking a number for prime in a way which prevents double checking. e.g (we DO NOT want thread0 to check if 1 is a prime because thread1 already did)
Your counter should be a value shared by all threads, so that incrementing it from one thread affects all concurrent threads.
Simplest way to do that is to use a static field. Then use some kind of synchronization to avoid threads incrementing / reading counter concurrently.
public class Main {
public static void main(String[] args) {
int logicalCores = Runtime.getRuntime().availableProcessors();
int startFrom = 0;
startCalc(logicalCores, startFrom);
}
public static void startCalc(int threadCount, int startFrom) {
PrimeCalculator.startAt(startFrom); //Set this for all threads
for (int i = 0; i < threadCount; i++) {
PrimeCalculator calculator = new PrimeCalculator(i);
Thread thread = new Thread(calculator);
thread.start();
}
}
}
import static java.lang.Thread.sleep;
public class PrimeCalculator implements Runnable {
static int counter; //Use static variable
int id;
public static void startAt(int counterStart) { //Set start once for all threads
counter = counterStart;
}
public PrimeCalculator(int id) {
this.id = id;
}
#Override
public void run() {
while (true) {
int current = incrementAndGetCounter();
if (isPrime((current))) {
System.out.printf("Thread with ID %d found that %d is a prime! \n", id, current);
try {
sleep(1000);
} catch (Exception e) {
}
}
}
}
public static boolean isPrime(int n) {
if (n == 2 || n == 3 || n == 5)
return true;
if (n <= 1 || (n & 1) == 0)
return false;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
//Use synchronized method to increment and get value
//to prevent one thread incrementing it while another one is reading it
private static synchronized int incrementAndGetCounter() {
return counter++;
}
}
Related
I am working on Thread for the first time and I tried to code an example I saw on the internet. An ArrayList of numbers must be divided into 4 parts, and 4 separate threads need to find the odd and even numbers in those parts and add them to the "evens" or "odds" list. Although I do not have any problems with the algorithm, I have problems with Threads.
Since the codes are not very long, I am adding them completely.
My Runnable Class:
package ThreadRace;
public class OddEvenFinder implements Runnable {
private final int id;
private final int size;
public OddEvenFinder(int id, int size) {
this.id = id;
this.size = size;
}
#Override
public void run() {
int start = id * this.size;
int end = start + this.size;
while (start < end) {
if (Starter.numbers.get(start) % 2 == 0) {
Starter.evens.add(start);
}
else {
Starter.odds.add(start);
}
start++;
}
}
}
My testing class:
package ThreadRace;
import java.util.ArrayList;
import java.util.List;
public class Starter {
public static List<Integer> numbers = new ArrayList<>();
public static List<Integer> evens = new ArrayList<>();
public static List<Integer> odds = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 10000; i++) {
numbers.add(i);
}
OddEvenFinder f1 = new OddEvenFinder(0, numbers.size() / 4);
OddEvenFinder f2 = new OddEvenFinder(1, numbers.size() / 4);
OddEvenFinder f3 = new OddEvenFinder(2, numbers.size() / 4);
OddEvenFinder f4 = new OddEvenFinder(3, numbers.size() / 4);
Thread thread1 = new Thread(f1);
Thread thread2 = new Thread(f2);
Thread thread3 = new Thread(f3);
Thread thread4 = new Thread(f4);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
System.out.println(evens.size());
System.out.println(odds.size());
}
}
When I run the application this way, the length of the evens and odds lists should be 5000-5000, but I get a result between 3000-4000.
Shouldn't the .join() function wait for threads to finish? How can there be numbers that are not included in the lists?
The interesting part is that the problem is almost resolved when I add a few words to debug.
When I edit the code like this:
#Override
public void run() {
int start = id * this.size;
int end = start + this.size;
while (start < end) {
System.out.println("Thread number " + (this.id + 1) + " is working");
if (Starter.numbers.get(start) % 2 == 0) {
System.out.println(start + " added to evens");
Starter.evens.add(start);
}
else {
System.out.println(start + " added to odds");
Starter.odds.add(start);
}
start++;
}
}
The output I get gives almost accurate results like 4999-5000. When I set the size of the numbers array to a smaller value such as 4000-5000, it gives the correct result.
I have 2 questions:
1- Why .join() is not working or what am I wrong about .join()?
2- How is it that printing a few texts makes the program run more accurately?
In the JavaDocs of ArrayList, it says in bold "Note that this implementation is not synchronised". So if several threads want to add an element at the same time, only the last call of the method will set the real value. The values of the other threads are simply overwritten. Therefore, you will get fewer numbers than expected.
In order for the list to be filled in a synchronised way, you should use the keyword "synchronized" as shown below.
synchronized (Starter.evens) {
Starter.evens.add(start);
}
and
synchronized (Starter.odds) {
Starter.odds.add(start);
}
We define balanced number as number which has the same number of even and odd dividers e.g (2 and 6 are balanced numbers). I tried to do task for polish SPOJ however I always exceed time.
The task is to find the smallest balance number bigger than given on input.
There is example input:
2 (amount of data set)
1
2
and output should be:
2
6
This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
private static final BigDecimal TWO = new BigDecimal("2");
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int numberOfAttempts = in.nextInt();
for (int i = 0; i < numberOfAttempts; i++) {
BigDecimal fromNumber = in.nextBigDecimal();
findBalancedNumber(fromNumber);
}
}
private static boolean isEven(BigDecimal number){
if(number.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0){
return false;
}
return true;
}
private static void findBalancedNumber(BigDecimal fromNumber) {
BigDecimal potentialBalancedNumber = fromNumber.add(BigDecimal.ONE);
while (true) {
int evenDivider = 0;
int oddDivider = 1; //to not start from 1 as divisor, it's always odd and divide potentialBalancedNumber so can start checking divisors from 2
if (isEven(potentialBalancedNumber)) {
evenDivider = 1;
} else {
oddDivider++;
}
for (BigDecimal divider = TWO; (divider.compareTo(potentialBalancedNumber.divide(TWO)) == -1 || divider.compareTo(potentialBalancedNumber.divide(TWO)) == 0); divider = divider.add(BigDecimal.ONE)) {
boolean isDivisor = potentialBalancedNumber.remainder(divider).compareTo(BigDecimal.ZERO) == 0;
if(isDivisor){
boolean isEven = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) == 0;
boolean isOdd = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0;
if (isDivisor && isEven) {
evenDivider++;
} else if (isDivisor && isOdd) {
oddDivider++;
}
}
}
if (oddDivider == evenDivider) { //found balanced number
System.out.println(potentialBalancedNumber);
break;
}
potentialBalancedNumber = potentialBalancedNumber.add(BigDecimal.ONE);
}
}
}
It seems to work fine but is too slow. Can you please help to find way to optimize it, am I missing something?
As #MarkDickinson suggested, answer is:
private static void findBalancedNumberOptimized(BigDecimal fromNumber) { //2,6,10,14,18,22,26...
if(fromNumber.compareTo(BigDecimal.ONE) == 0){
System.out.println(2);
}
else {
BigDecimal result = fromNumber.divide(new BigDecimal("4")).setScale(0, RoundingMode.HALF_UP).add(BigDecimal.ONE);
result = (TWO.multiply(result).subtract(BigDecimal.ONE)).multiply(TWO); //2(2n-1)
System.out.println(result);
}
}
and it's finally green, thanks Mark!
I just discovered the project euler website, I have done challenges 1 and 2 and have just started number 3 in java... here is my code so far:
import java.util.ArrayList;
public class IntegerFactorise {
private static int value = 13195;
private static ArrayList<Integer> primeFactors = new ArrayList<Integer>();
private static int maxPrime = 0;
/**
* Check whether a give number is prime or not
* return boolean
*/
public static boolean isPrimeNumber(double num) {
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
/*Multiply all of the prime factors in the list of prime factors*/
public static int multiplyPrimeFactors() {
int ans = 1;
for(Integer i : primeFactors) {
ans *= i;
}
return ans;
}
/*Find the maximum prime number in the list of prime numbers*/
public static void findMaxPrime() {
int max = 0;
for(Integer i : primeFactors) {
if(i > max) {
max = i;
}
}
maxPrime = max;;
}
/**
* Find all of the prime factors for a number given the first
* prime factor
*/
public static boolean findPrimeFactors(int num) {
for(int i = 2; i <= num; i++) {
if(isPrimeNumber(i) && num % i == 0 && i == num) {
//could not possibly go further
primeFactors.add(num);
break;
}
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
else {
return false;
}
}
/*start here*/
public static void main(String[] args) {
boolean found = false;
for(int i = 2; i < value; i++) {
if(isPrimeNumber(i) && value % i == 0) {
primeFactors.add(i);
found = findPrimeFactors(value / i);
if(found == true) {
findMaxPrime();
System.out.println(maxPrime);
break;
}
}
}
}
}
I am not using the large number they ask me to use yet, I am testing my code with some smaller numbers, with 13195 (their example) i get down to 29 in this bit of my code:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
It gets to the break statement then finally the check and then the return statement.
I am expecting the program to go back to the main method after my return statement, but it jumps up to:
findPrimeFactors(num / i);
and tries to finish the iteration...I guess my understanding is a flawed here, could someone explain to me why it is behaving like this? I can't wait to finish it of :) I'll find a more efficient way of doing it after I know I can get this inefficient one working.
You are using recursion, which means that a function will call itself.
So, if we trace what your function calls are when you call return, we will have something like that:
IntegerFactorise.main()
|-> IntegerFactorise.findPrimeFactors(2639)
|-> IntegerFactorise.findPrimeFactors(377)
|-> IntegerFactorise.findPrimeFactors(29) -> return true;
So, when you return in the last findPrimeFactors(), you will only return from this call, not from all the stack of calls, and the execution of the previous findPrimeFactors() will continue just after the point where you called findPrimeFactors().
If you want to return from all the stack of calls, you have to modify your code to do something like that:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
return findPrimeFactors(num / i);
}
So that when the last findPrimeFactors() returns, all the previous findPrimeFactors() which called it will return too.
I think the problem is that you are ignoring the return value from your recursive call to findPrimeFactors().
Let's walk through this. We start with the initial call to findPrimeFactors that happens in main. We then enter the for loop as it's the first thing in that method. Now let's say at some point we get into the else statement and thus recursively call frindPrimeFactors(num / i). This will suspend the looping, but as this recursive call starts to run you enter the for loop again (remember, the previous loop is merely paused and not finished looping yet). This time around you encounter the break, which allows this recursive call to finish out, returning true of false. When that happens you are now back to the original loop. At this point the original loop continues even if the recursive call returned true. So, you might try something like this:
if (findPrimeFactors(num / i))
return true;
I'm assuming that you need to continue looping if the recursive call returned false. If you should always finish looping upon return (whether true or false) then try this:
return findPrimeFactors(num / i);
I have an array with the size of n which is filled with the numbers 1..n.
I need to sum this array using m threads by each time taking two elements, sum them up and inserting the sum back to the array.
Here is what I tried to do.
The synchronized part first
public class MultiThreadedSum {
private ArrayBuffer ArrayBufferInst;
private int Sum;
private boolean Flag, StopFlag;
public MultiThreadedSum(ArrayBuffer ArrayBufferInst) {
this.ArrayBufferInst = ArrayBufferInst;
Sum = 0;
Flag = false;
StopFlag = false;
}
public synchronized void Sum2Elements() {
while(Flag){
try {wait();}
catch (InterruptedException e){}
}
Flag = true;
if (StopFlag) {
notifyAll();
return;
}
System.out.println("Removing and adding 2 elements.");
Sum = ArrayBufferInst.Sum2Elements();
notifyAll();
}
public synchronized void InsertElement() {
while(!Flag){
try {wait();}
catch (InterruptedException e){}
}
Flag = false;
if (StopFlag) {
notifyAll();
return;
}
System.out.println("Inserting the sum.");
ArrayBufferInst.InsertElement(Sum);
if (ArrayBufferInst.RetunrSize() == 1) {
StopFlag = true;
}
System.out.println(ArrayBufferInst);
notifyAll();
}
public boolean ReturnStopFlag(){
return StopFlag;
}
#Override
public String toString(){
return ArrayBufferInst.toString();
}
}
I've splitted the m threads to 2 groups, half of them will do the summarization and half will do the adding using wait and notify.
public class Sum2ElementsThread implements Runnable{
private MultiThreadedSum MultiThreadedSumInst;
public Sum2ElementsThread( MultiThreadedSum MultiThreadedSumInst){
this.MultiThreadedSumInst = MultiThreadedSumInst;
}
#Override
public void run() {
while(!MultiThreadedSumInst.ReturnStopFlag())
MultiThreadedSumInst.Sum2Elements();
}
}
public class InsertThread implements Runnable{
private MultiThreadedSum MultiThreadedSumInst;
public InsertThread( MultiThreadedSum MultiThreadedSumInst) {
this.MultiThreadedSumInst = MultiThreadedSumInst;
}
#Override
public void run() {
while(!MultiThreadedSumInst.ReturnStopFlag()) {
MultiThreadedSumInst.InsertElement();
}
}
}
Here is part of the main:
ArrayBufferInst = new ArrayBuffer(n);
System.out.println("The Array");
System.out.println(ArrayBufferInst);
MultiThreadedSumInst = new MultiThreadedSum(ArrayBufferInst);
ExecutorService Threads = Executors.newCachedThreadPool();
for (i = 0; i < m/2; i++)
Threads.execute( new Sum2ElementsThread(MultiThreadedSumInst) );
for (; i < m; i++)
Threads.execute( new InsertThread(MultiThreadedSumInst) );
Threads.shutdown();
while(!MultiThreadedSumInst.ReturnStopFlag()){}
System.out.println("The sum of the array is " + MultiThreadedSumInst);
And the buffer
public class ArrayBuffer {
private ArrayList<Integer> ArrayBufferInst;
public ArrayBuffer(int SizeOfBuffer){
int i;
ArrayBufferInst = new ArrayList<>(SizeOfBuffer);
for (i = 0; i < SizeOfBuffer; i++){
ArrayBufferInst.add(i, i+1);
}
}
public int Sum2Elements(){
if (ArrayBufferInst.size() < 2){
return -1;
}
return ArrayBufferInst.remove(0) + ArrayBufferInst.remove(0);
}
public void InsertElement(int Elem) {
ArrayBufferInst.add(Elem);
}
public int RetunrSize(){
return ArrayBufferInst.size();
}
#Override
public String toString() {
return ArrayBufferInst.toString();
}
}
My question is about the end of the main, sometimes the program stop, sometime it doesn't, I know all the threads are exiting the run method because I checked that.
Sometimes I see the The sum of the array is message, sometimes I don't.
Your problem lies here:
public synchronized void Sum2Elements() {
while(Flag){
try {wait();}
catch (InterruptedException e){}
}
Flag = true;
// rest of method omitted here
}
When this part of the program is executed for the first time Flag is false and the loop is ignored. All subsequent executions of this method will result in a deadlock since this is the only place where you set Flag to false.
Not even interrupting will work, since you have no break in your loop and after the interruption you just go on to the next cycle and wait() forever.
Oh and read this - Java is not c#
It is really a very long code for you task.
Maybe i can propose a different sollution.
You can just split array for m parts (m - is a number of threads) - and each thread would sum it`s own part. When summing is over in each Thread - just sum all part results.
Or maybe i didnt get your task correctly. Specify more details please (the full task).
I am having simple code of paralellizing QuickSort algorithm in Java, in run method I everytime create two seperate new threads for parallelizing processing of Array elements. But as it encounters join() statements for both created threads, threads never backs and halts on joins(), seems join() never releases them.
Below is the code.
class StartJoinQuickSort implements Runnable
{
private int m_Low, m_High;
private int[] m_Array = null;
private final static int NR_OF_VALUES = 10; // TOTAL_NO_VALUES
private int PivotElement;
private static Random m_random = new Random( );
public StartJoinQuickSort(int[] a_Array,int a_Low,int a_High)
{
this.m_Array = a_Array;
this.m_Low = a_Low;
this.m_High = a_High;
}
private void SwapArrayElements(int a_i,int a_j)
{
int temp = this.m_Array[a_i];
this.m_Array[a_i] = this.m_Array[a_j];
this.m_Array[a_j] = temp;
}// end of SwapArrayElements
private static int nextRandomFunctionValue(int aStart, int aEnd)
{
if ( aStart > aEnd )
{
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * m_random.nextDouble());
int randomNumber = (int)(fraction + aStart);
return randomNumber;
}// end of nextRandomFunctionValue
private static int[] GetArrayWithRandomValues()
{
int[] ArrayToBePopulatedWithRandomValues = new int[NR_OF_VALUES];
for(int index =0; index<NR_OF_VALUES;index++)
{
int RandomValue = StartJoinQuickSort.nextRandomFunctionValue(0,NR_OF_VALUES);
ArrayToBePopulatedWithRandomValues[index] = RandomValue;
}//end of for
return ArrayToBePopulatedWithRandomValues;
}//end of GetArrayWithRandomValues
private int middleIndex(int left, int right)
{
return left + (right - left) / 2;
}
public int Partition(int a_Start,int a_end)
{
// System.out.println("Partition ..thId : " + Thread.currentThread().getId());
int pivotIndex = 0;
int i = a_Start;
int j = a_end;
try
{
pivotIndex = middleIndex(a_Start , a_end);
this.PivotElement = this.m_Array[pivotIndex];
do
{
while(this.m_Array[i] < PivotElement )
i++;
if(j>0)
{
try
{
while( this.m_Array[j] > PivotElement )
j--;
}
catch(Exception ex){System.out.println(" j : " + j);}
}//end of if
if(i<=j)
{
SwapArrayElements(i,j);
// System.out.println("Swap .." + + Thread.currentThread().getId());
i++;
j--;
}//end of if
}while(i<=j);
}
catch(Exception except)
{
System.out.println("exception in Partition " + except);
}
return j;
}
public void run()
{
//System.out.println("in run..");
//System.out.println("after PARTITION");
StartJoinQuickSort oStartQuickSort_1 = null;
StartJoinQuickSort oStartQuickSort_2 = null;
if(this.m_Low < this.m_High )
{
int Index = Partition(this.m_Low,this.m_High);
Thread thPart_1 = new Thread ( new StartJoinQuickSort( this.m_Array,this.m_Low,Index ) );
Thread thPart_2 = new Thread ( new StartJoinQuickSort( this.m_Array,Index + 1,this.m_High ) );
thPart_1.start(); thPart_2.start();
//}//end of if
//if( Index + 1 < this.m_High)
//{
try
{
thPart_1.join(); thPart_2.join();
}catch (InterruptedException e) { e.printStackTrace();}
}
}//end of run
Regards
Usman
Hmmm, it is never a good idea to implement a recursive algorithm in parallel like this. You will end up creating a huge number of threads (exponential at every level) and will eventually oversubscribe the system.
The best idea is to have a cutoff point, which let's say is equal to the number of available cores. Then when the current level of recursion has a number of branches equal to the cutoff point switch to a sequential quicksort. Some very rough pseudocode of the flow:
parallel_quicksort(level, interval) {
// compute subintervals interval1, interval2
if(level < cutoff) {
spawn1: parallel_quicksort(level + 1, interval1);
spawn2: parallel_quicksort(level + 1, interval2);
join1();
join2();
} else {
quicksort(interval1);
quicksort(interval2);
}
}
Also have a look over this implementation to see if you've missed something: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm
What happens if you have e.g. low=0, high=1? If your Partition returns 1, you'll have an infinite loop of threads, right?
join() blocks if your thread doesn't finish. You need to determine why your threads are not finishing. Can you try debugging your program with a debugger?
Thanks all for your kind suggestions and advices.
I myself detected the problem. it was with Partition function which was not working fine, it was having some problems, I choose another one and it worked fine for me..
New Partition procedure is :
public int Partition(int[] a_Array, int a_Left, int a_Right)
{
// chose middle value of range for our pivot
int pivotValue = a_Array[middleIndex(a_Left, a_Right)];
--a_Left;
++a_Right;
while (true)
{
do
++a_Left;
while (a_Array[a_Left] < pivotValue);
do
--a_Right;
while (a_Array[a_Right] > pivotValue);
if (a_Left < a_Right)
SwapArrayElements(a_Left,a_Right);
else
{
return a_Right;
}
}
}