Java thread timing issue in my card game server - java

I have a timing issue and I don't know how to fix it.
In my second loop, Display card, it loops and each connection starts a class called cLookAtCardConnection. This class will sometimes set the flag mPlayerList.GetNextFlag(), thus causing the loop to exit and the program goes to the first loop, Turn card over, which calls the class cLookAtCardConnection
The problem is that after mPlayerList.GetNextFlag() is set, the next couple connections are still in the same loop and call the class cLookAtCardConnection instead of (exiting?) the loop when the flag is set and going into the loop that calls cLookAtCardConnection.
Why is there a delay in the loop exiting after the flag has been set?
while( lBoard.Next()==true)
{
mPlayerList.Next();
// inner loop wait for all players
/////////////////////////////////////////////////////////////////////////////
// turn one card over
mPlayerList.WaitForAllPlayers();
do
{
do{
r=GetClient();
switch(r)
{
case 0: return; // exitvon a very bad error
}
} while(r==2);// loop if it was a timeout
cTurnCardOvrerConnection thread = new cLookAtCardConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
} while( mPlayerList.AllPlayersFinished()==false);// end while
//////////////////////////////////////////////////////////////////////////
// Display card -LOOK AT CARD
mPlayerList.ClearNextFlag();
mPlayerList.WaitForAllPlayers();
do
{
System.out.println(Thread.currentThread()+": Display card \r");
do{
r=GetClient();
switch(r)
{
case 0: return; // exitvon a very bad error
}
} while(r==2);// loop if it was a timeout
cLookAtCardConnection thread = new cLookAtCardConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
// after this flag is set the next couple connectons are still in this loop???
} while( mPlayerList.GetNextFlag()==false);// end while
} // reloop game board
} // loop forever
// System.out.println("--------- Eit player loop ------------------- \r");
} catch(IOException ec)
{
System.out.println(ec.getMessage());
}
} // end run
} // end of class

You probably need to set up a synchronized block so that the code inside the do-while loop is only accessible to a single thread at a time.

Related

Implementing a simple turn-based game in Java using the wait-notify approach

I'm trying to implement a word game in Java, where each player takes turns extracting a number of random letters from a set, then trying to create a valid word with those letters. This is what I have so far (simplified for clarity's sake):
In the Game class, I start the game by running a thread for each player (and one for the timekeeper). I want the first player in the activePlayers list (which initially is the same as the players list) to make the first move, so I initialized the turn and turnIndex attributes to correspond to this player:
public void play()
{
this.turn = activePlayers.get(0); //the player who joined first goes first
this.turnIndex = 0; //the player's index in the ArrayList
for(Player player : players) {
new Thread(player).start();
}
new Thread(new Timekeeper()).start(); //keeps track of the game's duration
}
In the Player class, I want the players on stand-by to not do anything, and simply wait for the current player to finish their business, hence the first while loop. Then, when a player's turn has ended, I want that thread to yield the monitor to another player's thread and wait its next turn. This is how I decided to approach it:
private synchronized boolean submitWord() throws InterruptedException
{
while(game.turn != this)
{
System.out.println(this.name + " is waiting their turn...");
wait();
}
Thread.sleep(1000);
List<Tile> extracted = game.getBag().extractTiles(wordLength);
if(extracted.isEmpty())
return false; //if there are no more letters to extract, the thread ends its execution
//game logic goes here - creating and validating the word
//after this player is done, the next player makes their move
game.turnIndex++;
if(game.turnIndex >= game.activePlayers.size())
game.turnIndex = 0;
game.turn = game.activePlayers.get(game.turnIndex);
notifyAll();
return true;
}
#Override
public void run()
{
do {
try {
this.running = this.submitWord();
} catch(InterruptedException e) {
System.out.println("Something went wrong with " + this.name + "...");
e.printStackTrace();
}
} while(this.running);
game.activePlayers.remove(this); //the player is now inactive
if(game.winner == this)
System.out.println("Winner: " + this.name + " [" + this.score + " points]");
}
However, when I try to run the program, I get something like this:
Player 2 is waiting their turn...
Player 3 is waiting their turn...
1 seconds elapsed...
Player 1: AERIAL [36 points]
Player 1 is waiting their turn...
2 seconds elapsed...
3 seconds elapsed...
4 seconds elapsed...
5 seconds elapsed...
6 seconds elapsed...
Basically, the game doesn't move past Player 1's first try, and I get stuck in an infinite loop where nothing happens. Am I not using the wait() and notifyAll() methods properly? How should I make the player threads communicate with each other?
If I have understood your code correctly, that submitWord method belongs to the Player class. The keyword synchronized should be used to obtain the monitor of a shared resource to limit different threads from accessing the same resource at the same time and avoid race conditions.
In your case, you're synchronizing over a Player thread which is not the right design. You should synchronize instead over the shared resource which is the game object in this scenario. Besides, try to use synchronized blocks rather than entire synchronized methods, as the latter are more likely to block.
Within the Player's run method you should check whether the thread can acquire the game resource first with a synchronized block, if they do, then you can check whether it's the Player's turn by confronting the turn index of the game object with the Player's index. If it's not the Player's turn it invokes the wait() method; otherwise it carries on with its task by invoking submitWord.
Here, I've tweaked your code. You forgot a notify (or notifyAll) call when you were returning false in your submitWord method. That might have caused some stuck scenarios when there were no combinations available.
//Now, this method can be called only under the condition the the game's monitor lock has been already acquired. So, it can only be invoked within a synchronized block.
private boolean submitWord() {
List<Tile> extracted = game.getBag().extractTiles(wordLength);
if(extracted.isEmpty()){
//notify is more efficient than notifyAll as it causes less overhead by awakening only one random thread instead of all the ones waiting
this.game.notify();
//you were returning without notifying here... This might have caused some stucking scenarios...
return false;
}
//game logic goes here - creating and validating the word
//Rotating the turn
game.turnIndex = (this.game.turnIndex + 1) % this.game.activePlayers.size();
game.turn = game.activePlayers.get(game.turnIndex);
this.game.notify();
return true;
}
#Override
public void run() {
do {
synchronized(this.game){
if (this.game.indexTurn == this.index){
this.running = this.submitWord();
//It's more efficient to check here whether the player must be removed or not as you already own the game's lock
if (!this.running){
this.game.activePlayers.remove(this);
}
} else {
try {
this.game.wait();
} catch(InterruptedException e) {
System.out.println("Something went wrong with " + this.name + "...");
e.printStackTrace();
}
}
}
} while(this.running);
//you should re-acquire the game's lock here since you're modifying the set of players
//synchronized(this.game){
// this.game.activePlayers.remove(this);
//}
if(this.game.winner == this){
System.out.println("Winner: " + this.name + " [" + this.score + " points]");
}
}
Just a thought, but it could be that the sleep is happening within a synchronized method: Thread.sleep is blocking other thread also, working on other method, along with itself callled inside synchronized method

Selenium and Java: While loop not working as expected

I have a challenge with automating a click action and I'm struggling to understand what's wrong with the logic in my solution.
My challenge is that I need to click one of a number of different radio buttons.
Each radio button has an id of "r" + a_number.
I don't know, for any given test, what the available "r" + a_number options there will be, so I wrote this while loop, which is intended to click the first available radio button:
int counter = 0;
while(true) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
} catch (NoSuchElementException e) {
continue;
}
break;
}
This isn't working as intended - could someone help me understand what's wrong?
Note: I'm a novice with Java
Update
My aim is to click the first existing radio button, so the while loop increments the counter var, let's say r=1, then attempts to click a radio button with id "r1". If there is no such element with id "r1", a NoSuchElementException is thrown, in which case the current while loop iteration should stop and start the next iteration (r = 2, try to click element "r2", if does not exist, start next while loop cycle).
Suppose we get to element "r20" and this element does in fact exist, then the button should be clicked, the exception is not thrown and so the while loop continues and hits the break command, and the while loop is terminated.
The current behaviour, however, is that the exception does not get handled even when the element does not exist, the while loop terminates, but nothing has been clicked.`
There are two issues with the code:
Loop running only once- You are breaking the loop using break statement, after the first iteration itself.
No exception thrown- You are not logging the exception. You are only executing a 'continue' statement in the catch block. You do not need the statement because the loop will go to next iteration anyway (well after you remove the break statement).
You should use this code:
int counter = 0;
boolean foundElement = false;
while(!foundElement) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
foundElement = true;
} catch (NoSuchElementException e) {
//assuming you want to log exception. Otherwise you can leave the catch block empty.
System.out.println(e);
}
}
Not sure and may need little more information however, I would do it little differently
int counter = 0;
boolean ifNotFound = true;
while(ifNotFound) {
counter++;
try {
driver.findElement(By.id("r" + counter)).click();
ifNotFound = false;
} catch (NoSuchElementException e) {
System.out.println("exception caught");
}
}
I am just trying to click and if it is successful then will set the while loop to false and it will break.
It may be possible that the exception you are catching is not the one is being thrown so you may try to change it to generic Exception and if that works then you can catch more specific one or more than one if you need to.
Please use this:
int counter = 0;
while(true) {
counter++;
boolean elementFound = false;
try {
driver.findElement(By.id("r" + counter)).click();
elementFound = true;
} catch (NoSuchElementException e) {
continue;
}
if (elementFound){
break;
}
}

Concurrency issue in Java

I have a concurrency problem in Java that i'm to able to solve.
I want to set a timeout for a player to write an input and when it's turn is over I set a flag (player.myTurn) to false in another thread, which control the game logic, cause I want this thread to stay in the second while and set the timeout to infinity not to catching the SocketTimeoutException.
The problem is that after sending the command to the controllerServerSide on the last player input, this thread comes back to inputStream.readObject() before the variable myTurn is modified by the other Thread, so it set again the timeout, and this is a problem for the game.
How can I make this thread to wait until myTurn is changed (only over the last player input)?
ServerThread
public void run(){
while(!isStopped){
try {
while(!player.getMyTurn()){
socket.setSoTimeout(0);
}
socket.setSoTimeout(INPUT_TIMEOUT);
//ServerThread arrives here 'cause myTurn it isn't changed yet
String command = (String) inputStream.readObject();
socket.setSoTimeout(0);
controllerServerSide.receiveCommand(command);
}catch (IOException e) {}
GameThread
for(Player player : playerList){
if(!player.getConnectionState()){
player.setMyTurn(true);
//here it starts his turn
winner = turn.executeTurn(player);
//here it finish his turn
player.setMyTurn(false);
if(winner != null){
playerList.remove(winner);
break;
}
}
}
I'm sorry if this is a bad coding style, but I'm practically new to Java.
Thanks for your answers!

Thread, while loop and a System.out.print statement

Hi guys I have a nested Thread and using it to see when a player has taken a turn (in a draughts game) O have a game object and a public variable changedTurns.
new Thread() {
public void run(){
check();
}
private void check(){
boolean sent = false;
while(true){
System.out.println("ee"); \\line 9
if(game.changedTurns){
System.out.println("gg");
if(!sent){
System.out.println("ok");
sent =true;
}
}
}
}.start();
Everything works as expected like above I.e console shows plenty of "ee" followed by "gg" and then "ok" when the player takes their turn, however without line 9 nothing is shown when the player takes their turn ?!
You don't need to use threading to analyze whether the player has taken a turn. Just create a Player[] array and add a variable turn for the index of the player whose turn it is. Increment turn when a Player makes a turn.

How to break from a loop after the condition is met

Hi I have been trying for the past hour to break from this loop and continue since already met my condition once. My application pretty much reads a serie of lines and analyzes it and then prints the variable stated. An example of how the lines look like (the . are not included):
10 c = 9+3
20 a = c+1
30 print c
40 goto 20
50 end
It does everything right, when it gets to line 40 goes to line 20 as expected, but i want it to go to line 50 since already went to line 40 once. Here is my code for this part:
while(booleanValue)
{
if(aString.substring(0, 4).equals("goto"))
{
int chosenLine = Integer.parseInt(b.substring(5));
if(inTheVector.contains(chosenLine))
{
analizeCommands(inTheVector.indexOf(chosenLine));
i++;
}
else
{
System.ou.println("Line Was Not Found");
i++;
}
}
else if(aString.substring(0, 3).equals("end"))
{
System.out.println("Application Ended");
booleanValue = false;
}
}
Use the break statement to break out of a loop completely once your condition has been met. Pol0nium's suggestion to use continue would not be correct since that stops the current iteration of the loop only.
while(foo)
{
if(baz)
{
// Do something
}
else
{
// exit condition met
break;
}
}
All this having been said, good form dictates that you want clean entry and exit points so that an observer (maybe yourself, revisiting the code at a later date) can easily follow its flow. Consider altering the boolean that controls the while loop itself.
while(foo)
{
if(baz)
{
// Do something
}
else
{
// Do something else
foo = false;
}
}
If, for some reason, you can't touch the boolean that controls the while loop, you need only compound the condition with a flag specifically to control your while:
while(foo && bar)
{
if(baz)
{
// Do something
}
else
{
// Do something else
bar = false;
}
}
You could keep the code using booleanValue as-is and switch to a do-while loop.
do {
// ... existing code
} while (booleanValue);
However, to answer your specific question - you can always use the java break keyword. The continue keyword is more for skipping the remainder of the loop block and entering another loop iteration.
if you put this before your check for anything else, you would exit the loop immediately.
if(aString.substring(0, 3).equals("end")) {
break;
}
As an additional tip, you may want to use String.contains("end") or String.endsWith("end") instead of substring(). This way if a 1 or 3 digit (or more) number is used your code will still work.

Categories