Netbeans, red text but no error - java

I'm trying to implement a solution to the Dinning Philosophers. Not sure if I'm doing it right. My program isn't crashing but I am getting red text in the output, but there's no error code.
Example of the error:
at (package_name).Phil.getrightFork(Phil.java:70)
the error alternatives between line 70, and 46 (which is the line that calls getrightFork)
I've already swapping getrightFork with getleftFork, but it always selects the rightFork as the error
Here's the code I'm using:
Custom Semaphore:
public class Semaphore {
public int value= 0 ;
public Semaphore(int value) {
this.value = value;
}
public synchronized void up() { //notify must be syncrhonized
value++;
if (value > 0){
this.notifyAll();
}
}
public synchronized void down() throws InterruptedException {
while (value <= 0){//Check if resource is avaiable, if not WAIT.
this.wait();
}
value--; // Value is no longer negative
}}
main:
public class main {
private static final int N = 10000;
public static void main(String[] args) throws InterruptedException{
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i=0;i<N;i++){
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
phils[i].start();
}
for (int i=0;i<N;i++){
phils[i].join();
}
}}
Phil class:
public class Phil extends Thread {
Semaphore fork[];
int phil, total, left, right;
boolean leftFork = false, rightFork = false;
public Phil(int spot ,Semaphore[] s, int N){
phil = spot;
left = spot;
fork = s;
switch(spot){
case 0:
right = N-1;
break;
default:
right = spot - 1;
break;
}
}
public void run(){
System.out.println("I am Phil " + phil + " my left fork is " + left + " my right fork is " + right);
while(true){
try {
if (phil%2 == 0){
Thread.sleep(10); // Let the odd Phils eat first
}
getrightFork();
if (rightFork){
getleftFork();
}
if (leftFork && rightFork){
eat();
retleftFork();
retrightFork();
}
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
}
void getleftFork() throws InterruptedException{
fork[left].down();
//System.out.println("I got my left fork!");
leftFork = true;
}
void getrightFork() throws InterruptedException{
fork[right].down();
//System.out.println("I got my right fork!");
rightFork = true;
}
void retleftFork(){
fork[left].up();
leftFork = false;
}
void retrightFork(){
fork[right].up();
rightFork = false;
}
void eat(){
System.out.println("Phil:" + phil + " ate");
}}

You're getting a NullPointerException. The element in the array you are trying to access is null.
This is caused by the fact that you start your Phil before the entire array is complete...
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i = 0; i < N; i++) {
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
// Phil is starting, but how many phils are there??
phil.start();
}
Instead, try filling the array first and then starting them in a separate loop...
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i = 0; i < N; i++) {
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
}
for (Phil phil : phils) {
phil.start();
}
for (int i = 0; i < N; i++) {
phils[i].join();
}
If the solution requires that Phil be started as soon as they are created, then you need to change you checking code to handle the situation that the next element may be null

Related

so i am trying to print odd and even number using 2 threads but i am not getting the output i want, i want it to print in 1 to 10 in order

I am trying to learn Multi-threading and I am trying to print odd & even number using two thread but i am not sure how to synchronized the for loop and make it print from 1 to 10 in order.
public class Counter implements Runnable {
public static void main(String[] args) {
Thread t1 = new Thread(new Counter(1, " ODD")); // Thread 1 runs the Odd number
Thread t2 = new Thread(new Counter(0, " EVEN")); // Thread 2 runs the Even number
t1.start();
t2.start();
}
constructor:
int num; // gets the number
String name; // gets the name
public Counter(int i, String name) {
this.num = i;
this.name = name;
}
This is the Loop im using to create Odd and Even number and i dont know how to synchronized this loop.
public void printNum() {
synchronized (this) {
for (int j = this.num; j <= 10; j += 2) {
System.out.println(name + "-->" + j);
}
}
}
#Override
public void run() {
//this will run the printNum to the Threads
printNum();
}
Mb something like this
public class Counter implements Runnable{
#Override
public void run() {
try {
printNum();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args){
Thread t1 = new Thread(new Counter(1, " ODD")); // Thread 1 runs the Odd number
Thread t2 = new Thread(new Counter(0, " EVEN")); // Thread 2 runs the Even number
t2.start();
t1.start();
}
int num; // gets the number
String name; // gets the name
public Counter(int i, String name) {
this.num = i;
this.name = name;
}
public void printNum() throws InterruptedException {
synchronized (this) {
for (int j = this.num; j <= 10; j += 2) {
System.out.println(name + "-->" + j);
Thread.sleep(100);
}
}
}
}
Result:
public class HelloWorld {
public static void main(String[] args) {
counter e = new counter();
counter o = new counter();
e.neighbor = o;
o.neighbor = e;
e.wait = false;
o.wait = true;
e.count = 0;
o.count = 1;
Thread te = new Thread(e);
Thread to = new Thread(o);
te.start();
to.start();
}
static class counter implements Runnable{
public counter neighbor = null;
public boolean wait = false;
public int count = -1;
#Override
public void run(){
while (count <= 10){
if (!wait){
System.out.print("count = " + count + "\n");
count += 2;
wait = true;
neighbor.wait = false;
}
}
wait = true;
neighbor.wait = false;
}
}
}
Often when you have two threads interdependent on each other, like in these case where odd needs to wait until even has finished and vice versa, we need to establish some kind of relation in order for them to communicate with each other, the reason why your code wasn't working was because synchronize makes the thread wait until the other one has finished, in the loop however, the entire loop is considered one task and one thread will wait for the other to finish their loop first.

What is wrong with the my semaphore application?

The program's aim is to simulate that multiple users add a number to the buffer from 0 to n. Then print the sum of numbers in the buffer. When I run the program, it seems that the threads never end. However, the thread will finish when I run the program in debug mode of Idea and step line by line. Also, I do not exactly know where I need to use my semaphore method P() and V() for mutual exclusion.
Version: JDK 8. I cannot use semaphore in the library.
Main.java
Buffer b = new Buffer(bufferSize);
ArrayList<user> us = new ArrayList<>();
for(int i = 0; i < num_users; i++) us.add(new user(i, elements, b));
ArrayList<Thread> th = new ArrayList<>();
for(int i = 0; i < num_users; i++)
{
th.add(new Thread(us.get(i)));
th.get(i).start();
}
user.java
public class user implements Runnable
{
private int id;
private int num_elements;
private semaphore mutex = new semaphore(1 );
public static Buffer buf;
public user(int i, int el, Buffer b)
{id = i; num_elements = el; buf = b;}
public void add_elements()
{//Add element to buffer, element value iterates from 0, 1, 2 .... num_elements
mutex.P();
int n = 0;
while (num_elements > 0)
{
buf.add(new Integer(n));
n++;
num_elements--;
}
mutex.V();
}
public void run()
{
add_elements();
}
}
Buffer.java
public class Buffer
{
private LinkedList<Object> buf_list;
private int elements; //Number of elements currently on the queue
private int buf_size; //Maximum number of elements allowed on queue
private semaphore mutex = new semaphore(1);
public Buffer(int n) //Queue creation, with n indicating the maximum capacity
{
buf_list = new LinkedList<Object>();
elements = 0;
buf_size = n;
}
public void add(Integer n)
{
mutex.P();
buf_list.add(n);
elements++;
mutex.V();
}
public void finalSummation()
{
if (elements == buf_size)
{
mutex.P();
int sum = 0;
for (Object n : buf_list)
sum += ((Integer)n).intValue();
mutex.V();
System.out.println("Count total: " + sum);
}
}
}
semaphore.java
public class semaphore
{
private int count = 0;
public semaphore(int init_count)
{
count = init_count;
}
public synchronized void P()
{
count -= 1;
while (count < 0)
{
try {
wait();
} catch (InterruptedException e) {
System.out.println("Error");
System.exit(-1);
}
}
}
public synchronized void V()
{
count += 1;
notifyAll();
}
}
I expect it will print the sum of buffer numbers, but the thread may not finish.
There are a few things that stand out as issues here.
1) your code is never calling the finalSummation method. So the "printing" of the result will never happen.
2) Buffer and each user are all creating their own semaphores. If you are attempting to allow multiple threads to update Buffer without colliding then you need to share the same semaphore. Remove the semaphore and the usage of it from the user class. Just let the Buffer instance control only one update at a time with its semaphore.
3) You don't need to check the semaphore in the finalSummation method. Presumably, all threads are done at that point. And to enforce that ...
4) Put code like this at the end of main
for(int i = 0; i < num_users; i++) {
th.get(i).join();
}
b.finalSummation();
5) A semaphore should manage a number of permits. Your semaphore is managing the number of instances waiting - that is a pretty much an irrelevant number for a semaphore. Change your P() and V() to acquire() and release() to be consistent with the pattern.
public static class semaphore {
private int permits = 0;
public semaphore(int permits) {
this.permits = permits;
}
public synchronized void acquire() {
while (permits < 1) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Error");
System.exit(-1);
}
}
permits--;
}
public void release() {
synchronized (this) {
permits += 1;
notifyAll();
}
}
}
I have put it together using the above answer if that helps. Please select above answer as the right answer.
import java.util.ArrayList;
import java.util.LinkedList;
public class Main {
// assumed values
private static final int bufferSize = 5;
private static final int num_users = 10;
private static final int elements = 5;
public static void main(String[] args) {
Buffer b = new Buffer(bufferSize);
ArrayList<User> us = new ArrayList<>();
for(int i = 0; i < num_users; i++) us.add(new User(i, elements, b));
ArrayList<Thread> th = new ArrayList<>();
for(int i = 0; i < num_users; i++)
{
th.add(new Thread(us.get(i)));
th.get(i).start();
}
for(int i = 0; i < num_users; i++) {
try {
th.get(i).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
b.finalSummation();
System.out.println("Exiting");
}
}
class User implements Runnable
{
private int id;
private int num_elements;
public static Buffer buf;
public User(int i, int el, Buffer b)
{id = i; num_elements = el; buf = b;}
public void add_elements()
{//Add element to buffer, element value iterates from 0, 1, 2 .... num_elements
int n = 0;
while (num_elements > 0)
{
buf.add(new Integer(n));
n++;
num_elements--;
}
}
public void run()
{
add_elements();
}
}
class Buffer
{
private LinkedList<Object> buf_list;
private int elements; //Number of elements currently on the queue
private int buf_size; //Maximum number of elements allowed on queue
private Semaphore mutex ;
public Buffer(int n) //Queue creation, with n indicating the maximum capacity
{
buf_list = new LinkedList<Object>();
elements = 0;
buf_size = n;
mutex = new Semaphore(buf_size);
}
public synchronized void add(Integer n)
{
mutex.acquire();
buf_list.add(n);
elements++;
mutex.release();
}
public void finalSummation()
{
int sum = 0;
System.out.println(buf_list);
for (Object n : buf_list)
sum += ((Integer)n).intValue();
System.out.println("Count total: " + sum);
}
}
class Semaphore {
private int permits = 0;
public Semaphore(int permits) {
this.permits = permits;
}
public synchronized void acquire() {
while (permits < 1) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Error");
System.exit(-1);
}
}
permits--;
}
public void release() {
synchronized (this) {
permits += 1;
notifyAll();
}
}
}

How do you print out the value you get from call() function in callable?

public double[] call() throws Exception {
int [] zero = {0,0};
double [] return_to_thread = { };
List<Integer> MyList = new ArrayList<Integer>();
for(int i = 0; i < N_W; i++) {
if(MyList.size() == n) {
N++;
}
MyList.clear();
int [] initial_point = {x,y};
for(int istep = 0; istep < n; istep++) {
randomWalk(initial_point);
if(!MyList.contains(computeHashCode(initial_point)) && !MyList.contains(computeHashCode(zero))) {
MyList.add(computeHashCode(initial_point));
} else {
break;
}
}
if(MyList.size() == n) {
end_to_end_dis_sq += Math.pow(initial_point[0], 2) + Math.pow(initial_point[1], 2);
}
}
return_to_thread[0] += N;
return_to_thread[1] += S;
// System.out.print(return_to_thread);
Thread.sleep(3000);
return return_to_thread;
}
The code above is the call() function that will return an array with double as the type.
public static void main(String [] args) {
ExecutorService service = Executors.newFixedThreadPool(1);
List<Future<double[]>> list = new ArrayList<Future<double[]>>();
Callable<double[]> callable = new Callable_class_1a();
for(int i = 0; i < 1; i++) {
//Submit the task for execution.
Future<double[]> future = service.submit(callable);
list.add(future);
}
for(Future<double[]> futu : list) {
try {
System.out.print(Arrays.toString(futu.get()));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
service.shutdown();
}
}
}
And the code above is the main function that supposed to print out the value that I get from call() function. I ran this on Eclipse, and when I clicked run nothing happened.
I wonder what happened, and how do I solve this?
I can clarify any part that confused you.
This is my first every question on Stackoverflow, hope everyone treat me nicely :)

Unable to call getter for a Runnable in a ArrayList<thread>?

I know I can use callables to get a return value but is it possible to solve this without using it?
I am trying to get the tempCounter value from the primeThread and add them all into the counter. But I received a "symbol not found" error.
Is it possible for me the call the runnable method from the arrayList in the PrimeCounter class?
public class PrimeCounter {
public static void countPrimes() {
int counter = 0;
int primeNumbers = 2_534_111;
final int NUM_OF_THREAD = 4;
int startRange = 2;
int range = primeNumbers / NUM_OF_THREAD;
int endRange = startRange + range;
ArrayList<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < NUM_OF_THREAD; i++) {
threadList.add(new Thread(new primeThread(startRange, endRange)));
startRange += range;
if (endRange + range < primeNumbers) {
endRange += range;
} else {
endRange = primeNumbers;
}
}
for (Thread t : threadList) {
t.start();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
for (int i = 0; i < threadList.size(); i++) {
Thread tempThread = threadList.get(i);
while (tempThread.isAlive()) {
counter += tempThread.getCounter(); // symbol not found
}
}
System.out.println("\nNumber of identified primes from 2 to " + primeNumbers + " is :" + counter);
}
// checks if n is a prime number. returns true if so, false otherwise
public static boolean isPrime(long n) {
//check if n is a multiple of 2
if (n % 2 == 0) {
return false;
}
//if not, then just check the odds
for (long i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
primeThread Runnable
class primeThread implements Runnable {
private int startRange;
private int endRange;
private int threadCounter = 0;
public primeThread(int startRange, int endRange) {
this.startRange = startRange;
this.endRange = endRange;
}
#Override
public void run() {
for (int i = startRange; i < endRange; i++) {
if (Dumb.isPrime(i)) {
threadCounter++;
}
}
}
public int getCounter() {
return threadCounter;
}
First of all read about Java naming convention (your class names did't meet the convention)
With this fragment you say every thread to start, and before next tread to start main thread to wait the termination of this thread(Do you really want this?):
for (Thread t : threadList) {
t.start();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
Finally you get a thread from arrayList and you try to run a method that this thread don't have.
for (int i = 0; i < threadList.size(); i++) {
Thread tempThread = threadList.get(i);
while (tempThread.isAlive()) {
counter += tempThread.getCounter(); // symbol not found
}
}
getCounter is method for primeThread class, but you have Thread class!
You can fix this problem if your class primeThread extends Thread class.

Why isn't the bubbleDown method working as intended (Heap Sort)?

This was an assignment that was due, and I attempted it in both C++ and Java, but in both versions, the bubbleDown method wasn't working as intended, though I believe the logic says it should. I've already handed in both versions, but since the Java version is the most recent, I'll post it here.
Here's the Java version:
import java.io.*;
import java.util.Scanner;
public class HeapSort {
static int[] heap;
Integer[] sorted;
String in, out;
int fullLength = 0;
public HeapSort(String inf, String outf) throws FileNotFoundException {
in = inf;
out = outf;
Scanner scan = new Scanner(new File(in));
while (scan.hasNextInt()) {
fullLength++;
scan.nextInt();
}
sorted = new Integer[fullLength];
heap = new int[fullLength+1];
heap[0] = 0;
scan.close();
}
public boolean isFull() {
return heap[0] == fullLength;
}
public boolean isEmpty() {
return heap[0] == 0;
}
public void buildHeap() throws IOException {
Scanner scan = new Scanner(new File(in));
while (scan.hasNextInt())
insertOneDataItem(scan.nextInt());
scan.close();
}
public void deleteHeap() throws IOException {
while (!isEmpty()) {
deleteRoot();
printHeap();
}
}
public void deleteRoot() throws IOException {
if (isEmpty())
return;
FileWriter f = new FileWriter(out, true);
f.write("Deleting " + heap[1] + "\n");
f.close();
int i;
for(i = 0; sorted[i] != null; i++);
sorted[i] = heap[1];
heap[1] = heap[heap[0]--];
bubbleDown();
}
public void insertOneDataItem(int num) throws IOException {
if (isFull()) {
p("Heap is full");
return;
}
heap[++heap[0]] = num;
bubbleUp();
printHeap();
}
public void printHeap() throws IOException {
FileWriter f = new FileWriter(out, true);
f.write("Current Heap:\t");
for (int i = 1; i <= heap[0]; i++) {
if (i > 10) break;
f.write(heap[i] + " ");
}
f.write("\n");
f.close();
}
public void printSorted() throws IOException {
FileWriter f = new FileWriter(out, true);
f.write("Current Sorted:\t");
for (int i = 1; i <= sorted.length; i++) {
if (i > 10) break;
f.write(sorted[i] + " ");
}
f.write("\n");
f.close();
}
public void bubbleUp() {
int h = heap[0];
while (h >= 2 && heap[h] < heap[h/2]) {
int x = heap[h];
heap[h] = heap[h/2];
heap[h/2] = x;
h = h/2;
}
}
public void bubbleDown() {
int k = 1;
// make sure we have at least a left child
// before continuing on
while (2*k <= heap.length) {
int left = 2*k;
int right = 2*k+1;
if (heap[k] >= heap[left]) {
int x = heap[k];
heap[k] = heap[left];
heap[left] = x;
k = left;
continue;
}
if (right <= heap.length &&
heap[k] >= heap[right]) {
int x = heap[k];
heap[k] = heap[right];
heap[right] = x;
k = right;
} else {
return;
}
}
}
public void begin() throws IOException {
buildHeap();
deleteHeap();
printSorted();
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
p("Please start with: program file1.txt file2.txt");
System.exit(1);
}
// empty the output file
(new FileOutputStream(args[1])).close();
(new HeapSort(args[0], args[1])).begin();
}
public static void p(String s) {
System.out.println(s);
}
}
The input file (args[0]) with have only integers in the file, with some on the same row, and on different lines. args[1] is the output file name.
When the program goes through bubbleDown, it starts to work as intended in the beginning, but then it skips some numbers, and towards the end I'll eventually see a number that should have been at the top. Can someone explain to me what I did wrong in this function?
Your code looks suspicious for a number of reasons. 1 -- you are mixing the actual data structure implementation with reading a file which makes no sense. Very hard to follow. Then this piece can't be right:
sorted[i] = heap[1];
heap[1] = heap[heap[0]--];
First line suggests that heap array contains actual data elements.
But second line is treating heap contents as indexes of some sort? heap[0]-- will decrement the value stored at location 0 of the heap array, but first it will use it to move the contents of heap[heap[0]] to heap[1]? What? Are you using heap[0] as a special thing to store the index of the last element in the array? I suggest you start by rewriting code w/o hacks like this, it should make it easier to understand and fix. In reality your heap should start at element 0 and your left node will be at 2k+1 and right will be at 2k+2.
Now this smells like it is wrong:
right <= heap.length
you should be comparing right to that terrible heap[0], because heap.length will not be shrinking when you remove things from it.
for (int i = 1; i <= sorted.length; i++) {
should be
for (int i = 0; i < sorted.length; i++) {
and the final main mistake is in the bubbleDown method. When bubbling down you need to be swapping the downward shifting node with the smaller of its children. So that is 7 is bubbling down and its left child is 6 and right child is 4, you need to swap 7 and 4, otherwise you get invalid tree of
6
/ \
7 4
So code should be
if (heap[k] >= heap[left] && heap[left] < heap[right]) {
You are welcome. And your professor owes me lunch for doing his job for him.

Categories

Resources