Results 1 to 16 of 16

Thread: Java Run Order

  1. #1
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default Java Run Order

    I might not be the best java programmer but I thought java waited until the expression ran until it went to the next one, unless you're useing threads.
    In my program I run this code:
    Java Code:
    chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle);
    System.out.println("---Attemping to Connect...---");
    Thread.sleep(1000);
    chatDoc is a Styled Document.

    I thought java would first display the text in the Document, then println() and then sleep for 1 sec. However, first it runs println(), then sleeps for a sec, and then displays the text in the Doc. It is very important to my program that the code runs in order. Any ideas for why it doesn't run correctly?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Is this a Swing program?

  3. #3
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Yes, swingworker required?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Yes. If you call sleep on a Swing program, you put the EDT to sleep and no component painting (including text updates to text components) gets done. As you've already guessed, use a SwingWorker, and never call Thread.sleep on the EDT.

  5. #5
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Thanks, but that isnt the real problem, I just used Thread.sleep to find out the orderof output. My real program runs:

    Java Code:
    clientOS.write(username, 0, username.length());
    clientOS.newLine();
    clientOS.flush();
    clientOS is the client's output stream to a socket. The server is running:
    Java Code:
    String clientUser;
                while ((clientUser = serverIS.readLine()) != null)
                {
                   System.out.println("" + clientUser);
                   System.out.println("" + clientSocket.getInetAddress().getHostAddress());
                   break;
                }
                
                int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION);
    serverIS = server input stream
    Please note that the server code is running on a seperate Thread.

    In my test runs, I an connecting to myself (127.0.0.1) and I want the client to send the server it's username and the server will see this and be asked if they want to accept the connection. In the meantime, the client should see "attempting to connect...". Howver, when I test it, it doesnt display the attemtping to connect, and when the JDialog pops up there is nothing in the middle, just the frame, and then the program hangs. If you need I can post more code.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    It still smells like a threading issue. Yeah, please post more code if you can.

  7. #7
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Java Code:
    Thread waitForConnection = 
              new Thread() {
                 public void run() {
                   try {
                      echoServer = new ServerSocket(7890);
                      clientSocket = echoServer.accept();
                      handleClient();
                                        
                   } 
                       catch (IOException e) { handleException(e); waitForConnection.run(); }
                                  
                } 
             };
             
            
                               
           public void handleClient()
          {
             try
             {
                         			 
                
                serverIS = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                serverOS = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                String clientUser;
                while ((clientUser = serverIS.readLine()) != null)
                {
                   System.out.println("" + clientUser);
                   System.out.println("" + clientSocket.getInetAddress().getHostAddress());
                   break;
                }
                
                int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION);
                if (accept == 1){
                   
                   connected = false;
                   serverOS.write("no", 0, 2);
                   serverOS.newLine();
                   serverOS.flush();
                   serverIS.close();
                   serverOS.close();
                   clientSocket.close();
                   
                   return; }
                serverOS.write("yes", 0, 3);
                serverOS.newLine();
                serverOS.flush();
                
                while((input = serverIS.readLine()) != null)
                {
                   chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle);
                   scrollPaneToBottom();
                }
             }
                 catch (Exception e) {
                   handleException(e);
                }
                         
          }
       
       
       
       
       
           public void connect()
          {
             connected = false;
             int i=0;
             String check;
             try
             {
                hostname = JOptionPane.showInputDialog(null, "Connect to Host IP Adress as " + username + " :");
                chatSocket = new Socket(hostname, 7890);
                clientIS = new BufferedReader(new InputStreamReader(chatSocket.getInputStream()));
                clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket.getOutputStream()));
                chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle);
                System.out.println("---Attemping to Connect...---");
                clientOS.write(username, 0, username.length());
                clientOS.newLine();
                clientOS.flush();
                while(((check = clientIS.readLine()) != null) && !connected)
                {
                   if (check == "yes")
                   {
                      connected = true;
                      chatDoc.insertString(chatDoc.getLength(), "---Sucessfully Connected to " + hostname + "---\n", alertStyle);
                   } 
                   else {
                      chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + "---\n", alertStyle);
                   }
                   if ( i == 5000)
                   {
                      chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + ", Server would not respond(timeout)---\n", alertStyle);
                      break;
                   }
                   i++;
                }
                while((input = serverIS.readLine()) != null)
                {
                   chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle);
                   scrollPaneToBottom();
                }
             
                
                 
             } 
                 catch (Exception e) {
                   handleException(e);
                }
          
          }
    Note: thread waitForConnection is run in main(), and connect() is run from the Swing actionPreformed() with the hostIP as 127.0.0.1 (local)
    Last edited by collin389; 11-24-2009 at 05:39 AM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    connect() is run from the Swing actionPreformed()
    Meaning that connect() will be run on the EDT including Thread.sleep.

    And this code:
    Java Code:
                while((input = serverIS.readLine()) != null)
                {
                   chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle);
                   scrollPaneToBottom();
                }
    suggests that you're trying to manipulate Swing directly from within a background thread.


    Yeah you have some serious thread issues I believe. Also, you may want to fix these boys:
    Java Code:
    if (check == "yes")
    If you need more help, you may wish to learn about, create and post a Short, Self Contained, Correct (Compilable), Example or SSCCE for short. The link will show you how to do this. You will need to substitute all your connections and whatnots with Thread.sleep to emulate server-client connections or anything else that takes a bit of time to perform.
    Last edited by Fubarable; 11-24-2009 at 05:36 AM.

  9. #9
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Sorry, the Thread.sleep() shouldn't have been there, and whats wrong with if (check == "yes")

  10. #10
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    I think I know why, Because, when I call JDialog(), it uses EDT which is being used by connect, even though it is being called from it's own thread. Is there any way I could call connect() from the main Thread, or will i have to make a new one? Also, I still don't know why it wont display the text in chatDoc. Shouldn't it wait until the text is Displayed before it goes to the next line?

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by collin389 View Post
    Sorry, the Thread.sleep() shouldn't have been there
    Doesn't matter. All that connection stuff will likely put your app to sleep and should probably be done from within a SwingWorker. You can update the text fields via publish / process.

    and whats wrong with if (check == "yes")
    When you use == you are checking to see if two variables refer to the same object, but that's not what you want to know here. You want to know if the two String objects hold the same character sequence. That's why you always compare Strings with the equals(...) or equalsIgnoreCase(...) methods.
    Last edited by Fubarable; 11-24-2009 at 06:13 AM.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by collin389 View Post
    I think I know why, Because, when I call JDialog(), it uses EDT which is being used by connect, even though it is being called from it's own thread. Is there any way I could call connect() from the main Thread, or will i have to make a new one? Also, I still don't know why it wont display the text in chatDoc. Shouldn't it wait until the text is Displayed before it goes to the next line?
    I have no idea. You'll need to create an SSCCE for us to use your code and see what works and what doesn't.
    Last edited by Fubarable; 11-24-2009 at 06:14 AM.

  13. #13
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Its still pretty big, but it runs:
    Java Code:
       import java.awt.*;
       import java.util.*;
       import javax.swing.*;
       import javax.swing.text.*;
       import java.awt.event.*;
       import java.io.*;
       import java.lang.*;
       import java.net.*;
    
        public class CMessage extends JFrame implements ActionListener
       {
          String username = "Username";
          JMenuBar menuBar;
          JMenu fileMenu;
          JMenuItem itmConnect;
          JMenuItem itmDisConnect;
          JMenuItem itmQuit;
          JTextPane chatText;
          StyledDocument chatDoc;
          JScrollPane chatScroll;
          JTextField inputText;
          JScrollPane inputScroll;
          Style userStyle, clientStyle, alertStyle;
          boolean connected = false;
          String line;
          BufferedReader serverIS = null;
          BufferedWriter serverOS = null;
          BufferedReader clientIS = null;
          BufferedWriter clientOS = null;
          Socket clientSocket = null, chatSocket = null;
          ServerSocket echoServer = null;
          String input;
          String hostname;
       
           public CMessage()
          {
          //Menubar and menus
             menuBar = new JMenuBar();
          //File menu
             fileMenu = new JMenu("File");
             menuBar.add(fileMenu);
          //Connect Button
             itmConnect = new JMenuItem("Connect", KeyEvent.VK_C);
             fileMenu.add(itmConnect);
             itmConnect.addActionListener(this);
          //Disconnect Button
             itmDisConnect = new JMenuItem("Disconnect", KeyEvent.VK_D);
             fileMenu.add(itmDisConnect);
             itmDisConnect.addActionListener(this);
          //Separator
             fileMenu.addSeparator();
          //Quit Button
             itmQuit = new JMenuItem("Quit", KeyEvent.VK_Q);
             fileMenu.add(itmQuit);
             itmQuit.addActionListener(this);
          //End Buttons
          //End Menus
          //End Menubar
          
          
          //Add Chat Textarea
             chatText = new JTextPane();
             chatText.setEditable(false);
             chatText.setAutoscrolls(true);    
          	
             chatDoc = chatText.getStyledDocument();
          
             userStyle = chatText.addStyle("User", null);
             StyleConstants.setForeground(userStyle, Color.red);
             
             clientStyle = chatText.addStyle("Client", null);
             StyleConstants.setForeground(clientStyle, Color.blue);
             
             alertStyle = chatText.addStyle("Alert", null);
             StyleConstants.setForeground(alertStyle, Color.black);
             StyleConstants.setAlignment(alertStyle, StyleConstants.ALIGN_CENTER);
             
          	
          //Add Chat Textarea ScrollPane
             chatScroll = new JScrollPane(chatText);
          	
          
             
          	
          //Add all JFrame
             setLayout(new BorderLayout());
          	
             setJMenuBar(menuBar);
             add(chatScroll, BorderLayout.CENTER);
          }
       
       
       		
           public void actionPerformed(ActionEvent e) {
             String event = e.getActionCommand();
             if (event == "Connect") { connect(); }  
             if (event == "Disconnect") { disconnect(); } 
             if (event == "Quit") { disconnect(); System.exit(0);}     	
          }
       	
        	
       
          Thread waitForConnection = 
              new Thread() {
                 public void run() {
                   try {
                      echoServer = new ServerSocket(7890);
                      clientSocket = echoServer.accept();
                      handleClient();
                                        
                   } 
                       catch (IOException e) { handleException(e); waitForConnection.run(); }
                                  
                } 
             };
             
            
                               
           public void handleClient()
          {
             //connected = true;
             try
             {
                         			 
                
                serverIS = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                serverOS = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                String clientUser;
                while ((clientUser = serverIS.readLine()) != null)
                {
                   System.out.println("" + clientUser);
                   System.out.println("" + clientSocket.getInetAddress().getHostAddress());
                   break;
                }
                
                int accept = JOptionPane.showConfirmDialog( null, "Accept Connection Request from " + clientUser + " at: " + clientSocket.getInetAddress().getHostAddress() + "?", "Connection Request", JOptionPane.YES_NO_OPTION);
                if (accept == 1){
                   
                   connected = false;
                   serverOS.write("no", 0, 2);
                   serverOS.newLine();
                   serverOS.flush();
                   serverIS.close();
                   serverOS.close();
                   clientSocket.close();
                   
                   return; }
                serverOS.write("yes", 0, 3);
                serverOS.newLine();
                serverOS.flush();
                
                while((input = serverIS.readLine()) != null)
                {
                   chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle);
                
                }
             }
                 catch (Exception e) {
                   handleException(e);
                }
                         
          }
       
       
       
       
       
           public void connect()
          {
             connected = false;
             int i=0;
             String check;
             try
             {
                hostname = JOptionPane.showInputDialog(null, "Connect to Host IP Adress as " + username + " :");
                chatSocket = new Socket(hostname, 7890);
                clientIS = new BufferedReader(new InputStreamReader(chatSocket.getInputStream()));
                clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket.getOutputStream()));
                chatDoc.insertString(chatDoc.getLength(), "---Attemping to Connect...---\n", alertStyle);
                System.out.println("---Attemping to Connect...---");
                clientOS.write(username, 0, username.length());
                clientOS.newLine();
                clientOS.flush();
                while(((check = clientIS.readLine()) != null) && !connected)
                {
                   if (check == "yes")
                   {
                      connected = true;
                      chatDoc.insertString(chatDoc.getLength(), "---Sucessfully Connected to " + hostname + "---\n", alertStyle);
                   } 
                   else {
                      chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + "---\n", alertStyle);
                   }
                   if ( i == 5000)
                   {
                      chatDoc.insertString(chatDoc.getLength(), "---Failed to Connect to " + hostname + ", Server would not respond(timeout)---\n", alertStyle);
                      break;
                   }
                   i++;
                }
                while((input = serverIS.readLine()) != null)
                {
                   chatDoc.insertString(chatDoc.getLength(), input + "\n", clientStyle);
                
                }
             
                
                 
             } 
                 catch (Exception e) {
                   handleException(e);
                }
          
          }
       
       
       
       
       
       
       
           public void disconnect()
          {
             if (!connected) { 
                return; }
             try {
                if (echoServer != null) { echoServer.close(); }
                if (chatSocket != null) { chatSocket.close(); }
                if (clientSocket != null) { clientSocket.close(); }
                if (serverIS != null) { serverIS.close(); }
                if (serverOS != null) { serverOS.close(); }
                if (clientIS != null) { clientIS.close(); }
                if (clientOS != null) { clientOS.close(); }
                
             }
                 catch (Exception e) { handleException(e);  disconnect(); waitForConnection.run();}
                 
             connected = false;
          }
       
       
       
       
       
       
           public void handleException(Exception e)
          {
             JOptionPane.showMessageDialog(null,
                      "Error: " + e.getMessage(),
                      "Error",
                      JOptionPane.ERROR_MESSAGE);
          }
       
       
       
       
       
           public static void main( String args[] )
          {
             final CMessage window = new CMessage();
             window.setSize( 300, 400 );
             window.setTitle("Collin's Instant Messager");
             window.setVisible( true );
             window.setLocation( (0 ), (0));
             window.setResizable(true);
             window.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
             window.addWindowListener(
                    new WindowAdapter() {
                       public void windowClosing(WindowEvent we) {
                         window.disconnect(); System.exit(0);
                      }
                   });
             window.disconnect();
             window.waitForConnection.run();
          }
       }
    -you have to connect to 127.0.0.1

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I don't do client server apps, so I don't know if that portion is correct, but if I place stuff into a SwingWorker, it works better. for instance
    Java Code:
       public void connect() {
          connected = false;
             hostname = JOptionPane.showInputDialog(null,
                      "Connect to Host IP Adress as " + username + " :");
             //!! added
             if (hostname == null) { 
                return;
             }
             SwingWorker<String, String> worker = new SwingWorker<String, String>(){
                String check;
                int i = 0;
                
                @Override
                protected String doInBackground() throws Exception {
                   try {
                      chatSocket = new Socket(hostname, 7890);
                      clientIS = new BufferedReader(new InputStreamReader(chatSocket
                               .getInputStream()));
                      clientOS = new BufferedWriter(new OutputStreamWriter(chatSocket
                               .getOutputStream()));
                      
                      publish("---Attemping to Connect...---\n");
                      
                      System.out.println("---Attemping to Connect...---");
                      clientOS.write(username, 0, username.length());
                      clientOS.newLine();
                      clientOS.flush();
                      while (((check = clientIS.readLine()) != null) && !connected) {
                         if (check.equalsIgnoreCase("yes")) {
                            connected = true;
                            
                            publish("---Sucessfully Connected to " + hostname + "---\n");
                            
                         }
                         else {
                            
                            publish("---Failed to Connect to " + hostname + "---\n");
                         }
                         if (i == 5000) {
                            publish("---Failed to Connect to " + hostname
                                              + ", Server would not respond(timeout)---\n");
                            break;
                         }
                         i++;
                      }
                      while ((input = serverIS.readLine()) != null) {
                         publish(input + "\n");
    
                      }                  
                   }
                   catch (Exception e) {
                      handleException(e);
                   }
                   
                   return null;
                }
                
                protected void process(List<String> chunks) {
                   for (String chunk : chunks) {
                      try {
                         chatDoc.insertString(chatDoc.getLength(),
                                  chunk, alertStyle);
                      }
                      catch (BadLocationException e) {
                         e.printStackTrace();
                      }
                   }
                }
                
             };
             worker.execute();
          }

  15. #15
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    String a = "b"
    return (a == "b");
    that will return true so I don't understand the reason why you have to say
    return a.equals("b");
    they accomplish the same task.
    And thanks for taking the insult off, but I still saw it :)



    OK, nevermind. When i tested it i set String one = "one" and said (one == "one") ok, you're right. Thanks very much for all the help.
    Last edited by collin389; 11-24-2009 at 06:46 AM.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by collin389 View Post
    String a = "b"
    return (a == "b");
    that will return true so I don't understand the reason why you have to say
    return a.equals("b");
    they accomplish the same task.
    Strings are held in a String pool so that Java often will reuse a String object if it can. Thus it is often true that String variable a will == String variable b, but there is no guarantee. For instance, to force the issue, check out this:
    Java Code:
    public class Fu3 {
       public static void main(String[] args) {
          String str1 = "Foo";
          String str2 = new String("Foo");
          
          System.out.println(str1);
          System.out.println(str2);
          System.out.println("str1 == str2: " + (str1 == str2));
          System.out.println("str1.equals(str2): " + (str1.equals(str2)));
       }
    }
    And thanks for taking the insult off, but I still saw it :)
    Yeah, sorry for that. I spoke in haste and without thought.

Similar Threads

  1. Instantiation order
    By Jeremy720 in forum New To Java
    Replies: 3
    Last Post: 07-17-2009, 03:19 PM
  2. Sorting in descending order
    By santanu in forum New To Java
    Replies: 6
    Last Post: 11-26-2008, 11:43 PM
  3. Descending order
    By santanu in forum New To Java
    Replies: 1
    Last Post: 11-04-2008, 04:33 PM
  4. Replies: 0
    Last Post: 07-22-2008, 04:39 PM
  5. Replies: 0
    Last Post: 03-12-2008, 02:23 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •