I am trying to solve Philosopher Problem using Future in Java.
public class Philo implements Callable<PhiloStatus> {
private PhiloStatus status;
private Philo leftPhilo;
private Philo rightPhilo;
private String name;
public Philo(String name) {
status = PhiloStatus.THINKING;
this.name =name;
}
public void setLeftPhilo(Philo leftPhilo) {
this.leftPhilo = leftPhilo;
}
enter code here
public void setRightPhilo(Philo rightPhilo) {
this.rightPhilo = rightPhilo;
}
#Override
public PhiloStatus call() throws Exception {
if (leftPhilo.getStatus() == PhiloStatus.THINKING
&& rightPhilo.getStatus() == PhiloStatus.THINKING) {
this.status =PhiloStatus.DINING;
System.out.println("Dininig "+this);
return PhiloStatus.DINING;
}
this.status =PhiloStatus.THINKING;
System.out.println("Thinking "+this);
return PhiloStatus.THINKING;
}
public PhiloStatus getStatus() {
return status;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return name;
}
}
Starting point of the program
public class Start {
/**
* #param args
*/
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
Philo[] philosophers = new Philo[5];
for (int i = 0; i < 5; ++i)
philosophers[i] = new Philo(""+i);
for (int i = 0; i < 5; ++i) {
philosophers[i].setLeftPhilo(philosophers[(i + 4) % 5]);
philosophers[i].setRightPhilo(philosophers[(i + 1) % 5]);
executorService.submit( philosophers[i]);
}
}
}
But seems like once Callable is finished executing , it returns the same result.
I doubt now that it might not be possible to solve this problem using Future?
Could anyone please shed a light on this.
class Philo implements Runnable{
#Override
public void run(){
while(true){
if(Thread.interrupted()){
break;
}
//dining logic
}
}
}
The solution can be a loop which executes till someone interrupts the Philosopher.
A Callable computes the result once, then returns the value for this computation. So if you want to compute something again, you need to run the Callable again.
void diningAttempt() {
Future<PhiloStatus>[] results = new Future<PhiloStatus>[philosophers.length];
for (int i = 0; i < philosophers.length; ++i) {
results[i] = executor.submit(philosophers[i]);
}
for (int i = 0; i < philosophers.length; ++i) {
System.out.println(results[i].get());
}
}
And then somewhere else:
while (dining) {
diningAttempt();
}
As you can probably see, this is slightly different to what the “Dining Philosopher” problem actually describes, which is the problem of threads being able to do something at any time, as in this case you have separated dining attempts, which then most likely succeed all the time.
If you want those threads to actually lock, you need to give them the ability to run in parallel all the time, which means a Callable is not the correct way to simulate this issue. Nevertheless your attempt has a valuable lesson to learn: if you manage to put your work in separate batches like above, threads are much less likely to lock. And this is why the Executor has been invented in the first place.
Related
I tried out multithreading for a project I'm making. in the project I need to do a certain calculation multiple times every time I call for a certain function. I tried making some testing code to understand how to do it, but I can't get it to work properly (the code seems to work perfectly when I debug it, but if I run it normally it doesn't work past the first cycle).
in the code there is an endless loop that mimics my project's calling for a function multiple times. I tried to do it so the thread runs while changeflag is true, and change the flag to false after every run of the calculation so it would stop from calculating it again and again, and after "calling" the function I change it to true back, so it would be able to calculate again.
following is my code:
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Result> queue = new SynchronousQueue<>();
int loops = 0;
MyThread[] arr = new MyThread[10];
ArrayList<Result> ress = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
arr[i] = new MyThread(i, queue);
arr[i].start();
}
while (true) {
System.out.println(loops++);
while (ress.size() < arr.length){
ress.add(queue.take());
}
while (!ress.isEmpty()){
arr[ress.get(0).getSign()].setChangeflag(true);
ress.remove(0);
}
}
}
}
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class MyThread extends Thread{
private boolean changeflag = true;
private boolean runflag = true;
private int sign;
private BlockingQueue<Result> queue;
Random rnd = new Random();
public MyThread(int sign, BlockingQueue<Result> queue){
this.sign = sign;
this.queue = queue;
}
public void run(){
while (runflag){
if(changeflag){
changeflag = false;
try {
queue.put(sense());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public Result sense(){
return new Result( rnd.nextInt(10), sign);
}
public synchronized void setChangeflag(boolean changeflag) {
this.changeflag = changeflag;
}
}
public class Result {
private double res;
private int sign;
public Result(double res, int sign) {
this.res = res;
this.sign = sign;
}
public int getSign() {
return sign;
}
}
I recommend using Executors.newCachedThreadPool(). This will return an ExecutorService which you can use to queue your calculations using submit(Callable), which returns a Future on which you can block as desired. If you queue many tasks you can just keep a list of Futures as needed or a list of tasks then submit them to the ExecutorService.
Also note it's usually not recommended to extend from Thread.
Hope this helps!
The only reason I, at least, can see why you need Threads here is to do other work while waiting for the sense method to complete in the background. For example render some graphics or interact with the user.
If your main Thread is required to wait until all the sense job is complete for each request, then you don't need Threads. Just call the method sense directly in the main Thread.
On the other hand, if you need a background Thread doing the sense job while the main Thread is doing other work, then you will need two Threads: one is the main, and the other is the background-job. Then you probably need to have a producer-consumer pattern, where the producer (the main Thread) creates the requests and the consumer (the background Thread) executes the sense method. But then it seems like the roles are turned around again like you want to wait in the main Thread all the requests to complete after you submit them. If that is the case then you can start all the MyThreads and then call join on them when you are ready to wait for their results. For example:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
public class Main {
public static class Result {
private final int index;
private final Object value;
public Result(final int index,
final Object value) {
this.index = index;
this.value = value;
}
public int getIndex() {
return index;
}
public Object getValue() {
return value;
}
}
public static class MyRunnable implements Runnable {
private final int index;
private final Collection<Result> sharedResults;
public MyRunnable(final int index,
final Collection<Result> sharedResults) {
this.index = index;
this.sharedResults = Objects.requireNonNull(sharedResults);
}
#Override
public void run() {
final Result res = sense(); //Calculating outside the synchronized block.
synchronized (sharedResults) { //Synchronizing, because the actual instance of this collection might not be synchronized.
sharedResults.add(res);
}
}
private Result sense() {
return new Result(index, "Value" + index);
}
}
public static void main(final String[] args) {
final Thread[] t = new Thread[10];
final Collection<Result> sharedResults = new ArrayList<>();
for (int i = 0; i < t.length; ++i) {
t[i] = new Thread(new MyRunnable(i, sharedResults));
t[i].start();
}
for (final Thread thread: t)
try { thread.join(); } catch (final InterruptedException ix) { ix.printStackTrace(); }
sharedResults.forEach(res -> System.out.println("Result " + res.getIndex() + " with value \"" + res.getValue() + "\"."));
}
}
Another way is to use an ExecutorService like suggested by #m0skit0 and utilize the returned Future objects to wait for the results.
i have a class who extends from Thread:
public class Generador extends Thread {
...
public Generador(int marca, float sleep) {
this.marca = marca;
this.sleep = sleep;
this.cantActivaciones = 0;
}
#Override
public void start() {
marcadorAct++;
cantActivaciones++;
if (marcadorAct == 3) {
desalojarPasajero = true;
marcadorAct = 0;
} else {
desalojarPasajero = false;
}
}
#Override
public void run() {
System.out.println("The thread is running.....");
}
My problem is that the method run() is not working when i use the start() method. Here is my code:
public class Simulación {
...
Generador generador[] = new Generador[30]; // Arr of threads...
public Simulación() { // The constructor
....
for (int i = 0; i < generador.length; i++) {
generador[i] = new Generador((i + 1) * 1000000, rand.nextInt(3) + rand.nextFloat());
}
....
}
public void generarPasajero() { // The method who decides to start a thread...
for (int i = 0; i < generador.length; i++) {
if (!generador[i].isAlive()) {
generador[i].start(); // HERE START DOESNT RUN THE RUN() METHOD
break;
}
}
}
I hope you could understand my problem..
Anyone can help me with this? Thank you!
By overriding the start() method, you prevent what the method would have done on it own, because you replaced the code it executes. That means it won't start a thread by running the run() method.
This page from Geeks for Geeks explains it pretty well.
The best practice would be to move all your code to the run function. The start function from the Thread class is overridden in your implementation.
Additionally, your class would be a valid Runnable class. If the task need to be started without starting a new thread, the run() function can be called.
I'd like to implement my own semaphore in Java (just for practice, I am aware, that there is Semaphore class)
I have implemented it like that:
public class MySemaphore {
private int value = 1;
public synchronized void take() {
this.value++;
this.notify();
}
public synchronized void release(){
while (this.value == 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
this.value--;
}
}
I am trying to use it in such thread:
public class MyThread extends Thread {
private static MySemaphore semaphore = new MySemaphore();
public void run(){
for (int i = 0; i < 100; i++) {
semaphore.take();
try {
Main.myVariable += 1;
semaphore.release();
} catch (Exception e){
System.out.println("Exception" + e.getMessage());
}
}
}
}
I start and join threads like this:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int myVariable = 0;
private static int threadsNumber = 100;
public static void main(String[] args) {
List<Thread> allThreads = new ArrayList<>();
for (int i = 0; i < threadsNumber; i++) {
allThreads.add(new Thread(new MyThread()));
}
for (int i = 0; i < threadsNumber; i++) {
allThreads.get(i).start();
}
for (int i = 0; i < threadsNumber; i++) {
try{
allThreads.get(i).join();
} catch (Exception e){
System.out.println(e.getMessage());
System.out.println("********************************");
}
}
System.out.println("Result is " + myVariable);
}
}
I just want to increment a variable 10000 times and receive a result. Without semaphore the result is less than 10000 (like 9923, 9684), which is caused by non-atomicity of incrementation. I want to protect this variable using semaphore.
Unfortunately, the result is still less than or equal to 10000 (but much closer, in 9 out of 10 cases greater than 9990).
Do you have any idea why it happens? Is my semaphore wrong or am doing something wrong with launching threads?
In your MySemaphore class, value is already set to 1. It should be zero because in your release function you are verifying if value equals zero or not. This means that when your program starts, no thread will be able to have the semaphore(because you have set it to 1); doing so, they fall into waiting state. Your program ends when 'threadsNumber' reaches it's limit.In other words, you are not verifying if any thread is in waiting state before the programs ends. This explains why you have a 9/10 as success rate.
My recommendation would be to try setting the value to zero and also verify if there are any threads in waiting state.
Your code be like this:
public class MySemaphore {
private int value = 0; //this is already an error in your code
public synchronized void take() {
this.value++;
this.notify(); // wakes up the first thread that called wait on the shared variable
}
public synchronized void release() throws InterruptedException{
while(this.signals == 0) wait();
this.value--;
}
}
I am working through Bruce Eckel's Thinking in Java 4th edition.
In the chapter on concurrency there is an exercise on race conditions, when they might occur and how to prevent them.
Unfortunately I cannot seem to replicate the race condition when extending a simple Thread, but using the same code in a Runnable and an ExecutorService I do get the race condition.
Can anyone explain the difference?
My basic class which must always be even:
class EvenNumber {
private int value=2;
public int getValue(){
return value;
}
public boolean validate(){
if (value%2 !=0) {
System.err.println(value + " is not an even number!");
throw new RuntimeException();
}
return true;
}
protected void addTwo(){
++value;
Thread.yield(); //problem should occur here
++value;
}
//public mutator
public void addLotsOfTwos(int n){
for(int i=0;i<n;i++){
addTwo();
}
}
}
Extending a thread I can't seem to be able to get a race condition going.
class EvenCheckerThread extends Thread {
private static int counter =0;
private final int id;
private EvenNumber even;
EvenCheckerThread(EvenNumber even){
this.id = ++counter;
this.even = even;
}
public void run(){
System.out.println("Start thread#" + id + "using " + even);
for(int i=0; i<10 ;i++){
even.addLotsOfTwos(10);
even.validate();
}
System.out.println("Finish thread#" + id);
}
}
Exactly same code in a Runnable quickly throws an exception:
class EvenCheckerRunnable implements Runnable {
private static int counter =0;
private final int id;
private EvenNumber even;
EvenCheckerRunnable(EvenNumber even){
this.id = ++counter;
this.even = even;
}
public void run(){
System.out.println("Start thread#" + id + "using " + even);
for(int i=0; i<10 ;i++){
even.addLotsOfTwos(10);
even.validate();
}
System.out.println("Finish thread#" + id);
}
}
I try and test my classes from E11.main(). However, passing the same EvenNumber object to the Thread doesn't give me an exception even though I've created 100 threads, they all seem to start and finish nicely in order.
Creating 10 threads using Executors quickly throws an exception.
public class E11 {
public static void main(String[] args) {
EvenNumber even = new EvenNumber();
for(int i=0;i<100;i++){
new EvenCheckerThread(even).run();
}
/*ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
exec.execute(new EvenCheckerRunnable(even));
}*/
}
}
I'm sure I've misunderstood something at a very basic level, but I don't know what...
This piece of code:
for(int i=0;i<100;i++){
new EvenCheckerThread(even).run();
}
does not run the code in new Thread, so everything gets properly executed in one single sequence. You created an instance of the class Thread, but the run() method simply executes on the current Thread. Instead, try to call the start() method to actually start a new Thread.:
for(int i=0;i<100;i++){
new EvenCheckerThread(even).start();
}
This is for testing proposes (nothing bad)
I want to make a bruteforce program with Selenium 2 who breaks in a "0 to 10" password protected page
i have this (a tiny example not the actual code) ...
public class test implements Runnable {
static WebDriver driver;
test() {
StageLoader();
Thread t = new Thread(this);
t.start();
}
//starts firefox and goes to the page
private void StageLoader() {
driver = new FirefoxDriver();
driver.get("http://test.com/login.php");
}
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
bruteForce(i);
}
}
private void bruteForce(int i) {
driver.findElement(
By.name("password"))
.sendKeys(Integer.toString(i));
String output = driver.findElement(By.id("result")).getText();
if (output.indexOf("sucess") != -1) {
//stop
} else {
//continue
}
}
public static void main(String[] args) {
new FiberBrute();
}
}
it works perfectly but it lacks synchronization, i want it to go from 0 to 10 one by one and only continue with the next if !success, i already tried a lot to make this works with concurrency but i failed :( can you help me a little please ?
thanks in advance :D
The example code here as written should go 1 by 1, but it won't stop on success.
#Override
public void run() {
// Go until we run out of numbers or bruteForce comes back with 'true'
for (int i = 0; i <= 10 && !bruteForce(i); i++);
}
//Returns true if it found the password
private boolean bruteForce(int i) {
driver.findElement(
By.name("password"))
.sendKeys(Integer.toString(i));
String output = driver.findElement(By.id("result")).getText();
if (output.indexOf("sucess") != -1) {
//stop
return true;
} else {
//continue
return false;
}
}
In order for all 10 attempts to happen at once, bruteForce would need to be spawning threads, which it isn't doing here.