Need to stop servlet execution until another thread completes its execution

Hi all,
i created servlet & in the doPost method i run a thread,after the thread end its execution, the servelt takes a result from this thread & do something in it.
my problem is that , i need to make the servlet stop the execution until this thread ends, & then the servlet continue in executing the remaining code.
welcome to any help.

This appears to be a threads related problem. Try Thread.join - http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#join()

Similar Messages

  • Stop execution until GUI is completed

    I wrote a program to monitor a seniority list. If an odd last name, first name, etc is encountered, a gui opens to request the proper form of the name. The problem is that the program keeps running even though the gui has not yet been fililed out. How do I stop execution until the GUI is completed?
    Thanks
    Joe

        public static void readFile2(String lnames   [], String fnames[], String mnames[],
                                     String facs     [], String sdates[], String scores[],
                                     String scrambles[], String filename)
            String tempTitle = "JR";
            System.out.println("Inside ReadFile");
            try
                System.out.println("Inside Try");
                BufferedReader in = new BufferedReader(new FileReader( filename ));
                        //"C:/Documents and Settings/Joe/JavaApplication1/src/test.txt"));
                String tempElement  = "";
                //String tempElements[15];
                String tempElement1 = "";
                String tempElement2 = "";
                String tempElement3 = "";
                String tempElement4 = "";
                String tempElement5 = "";
                String tempElement6 = "";
                String tempElement7 = "";
                String tempElement8 = "";
                String tempElement9 = "";
                String tempElement10 = "";
                String tempElement11 = "";
                String tempElement12 = "";
                StringTokenizer data;
                String S;
                int numberOfTokens = 0;
                int numberOfWords  = 0;
                int numberOfLines  = 0;
                S = in.readLine();
                data = new StringTokenizer(S);
                numberOfTokens = data.countTokens();
                //System.out.println("Next Token " + data.nextToken());
                //System.out.println(data);
                //array[row][col]
                System.out.println("Ready to Tokenize");
                int i = 0;
                int q = 0;
                int lineCount = 0;
                while( ( ! S.equals("") ) && (data.hasMoreTokens() )
                                          && (S.trim().length() != 0))//in.readLine()
                    int col = 0;
                    int j = 0;
                    //while( i < SenListHelpers.getArrayLength(tempElements2) )
                        while( data.hasMoreTokens() )
                            tempElements1[i][j] = data.nextToken();    //get LName
                            System.out.println(" Getting tempElements1[ " + i + " ]" + "[ " + j + " ]" + tempElements1[i][j]);
                            //System.out.println("tempElements [" +  i  +  "] "    + tempElements1[i][j]);
                            j ++;
                        i ++;
                        System.out.println(" i = " + i );
                        int p = 0;
                        System.out.println("tempElements [" +  q  +  "] "    + tempElements1[q][p]
                                                                       + " " + tempElements1[q][p+1]
                                                                       + " " + tempElements1[q][p+2]
                                                                       + " " + tempElements1[q][p+3]
                                                                       + " " + tempElements1[q][p+4]
                                                                       + " " + tempElements1[q][p+5]
                                                                       + " " + tempElements1[q][p+6]);
                        q ++;    
                        //#2
                            ( compareStringByCase(tempElements1[lineCount][0], "DE"    ) ) ||
                            ( compareStringByCase(tempElements1[lineCount][0], "LE"    ) ) ||   
                            ( compareStringByCase(tempElements1[lineCount][0], "LA"    ) ) ||
                            ( compareStringByCase(tempElements1[lineCount][0], "MC"    ) ) ||  
                            ( compareStringByCase(tempElements1[lineCount][0], "ST"    ) ) ||
                            ( compareStringByCase(tempElements1[lineCount][0], "ST."   ) ) ||   
                            ( compareStringByCase(tempElements1[lineCount][0], "VAN"   ) ) ||    
                            ( compareStringByCase(tempElements1[lineCount][0], "EL"    ) )
                        if( ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "DE"    ) ) ||
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "LE"    ) ) ||   
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "LA"    ) ) ||
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "MC"    ) ) ||  
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "ST"    ) ) ||
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "ST."   ) ) ||   
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "VAN"   ) ) ||    
                            ( SenListHelpers.compareStringByCase(tempElements1[lineCount][0], "EL"    ) ) )
                            System.out.println("");
                            correctOfficerGUI test = new correctOfficerGUI(tempElements1, lineCount);
                            test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
                            return;// from this method;
    //Here is the GUI class
    public class correctOfficerGUI extends JFrame
            private final JTextField nameInfo, lname, fname, mname, sdate, score, scramble;
            private JPanel form;
            private final JFrame f;
            //EASTERN NY
            public static String nameInfoString   = new String();
            String facilities[] = {     
            "ADIRONDACK",     "ALBION",    "ALTONA", "ARTHUR KILL", "ATTICA",                         
         "AUBURN CORR",  "BARE HILL", "BAYVIEW",     "BEACON", "BEDFRD HILL",                    
            "BUFFALO",      "BUTLER",    "BUTLER ASAT", "GABRIELS",     "GEORGETOWN",                    
         "PHARSALIA",     "CAPE VINCEN", "CAYUGA", "CHATEAUGAY", "CLINTON COR",     
         "COLLINS",     "COXSACKIE", "DOWNSTATE", "EASTERN NY", "EDGECOMBE",                    
         "ELMIRA CNTR",  "FISHKILL",  "FIVE POINTS", "FRANKLIN", "FULTON FAC",                    
         "GOUVERNEUR",     "GOWANDA", "GREAT MEADW", "GREEN HAVEN", "GREENE",                         
         "GROVELAND",     "HALE CREEK", "HUDSON", "LAKEVIEW", "LAKEVIEW ASA",
         "LINCOLN FAC",     "LIVINGSTON", "LYON MTN", "MARCY", "MID-ORANGE",                    
         "MID STATE",     "MOHAWK",     "MONTEREY", "MORIAH SICF", "MT MCGREGOR",     
            "NYC CTL ADM",  "OGDENSBURG", "ONEIDA",  "ORLEANS", "OTISVILLE",                    
         "QUEENSBORO",     "RIVERVIEW",  "ROCHESTER", "SHAWANGUNK", "SING SING",                    
         "SOUTHPORT",     "SULLIVAN",   "SUMMIT",     "TACONIC C F", "ULSTER",                         
         "UPSTATE",     "WALLKILL",  "WASHINGTON", "WATERTOWN", "WENDE",                         
         "WILLARD",     "WOODBOURNE", "WYOMING"};
        public correctOfficerGUI(String[][] array, int lineCount)
            //JFrame
            f = new JFrame("Add Officer");
            // Make a panel to hold the demo �form", then
            // add it to the top of the frame�s content pane
            //JPanel
            form = new JPanel();
            f.getContentPane().setLayout(new BorderLayout());
            f.getContentPane().add(form, BorderLayout.NORTH);
            // Set the form panel�s layout to GridBagLayout
            // and create a FormUtility to add things to it.
            form.setLayout(new GridBagLayout());
            FormUtility formUtility = new FormUtility();
            // Add some sample fields
            System.out.println(array[lineCount][0] + " " + array[lineCount][1] + " " +
                               array[lineCount][2] + " " + array[lineCount][3] + " " +
                               array[lineCount][4] + " " + array[lineCount][5] + " " +
                               array[lineCount][6] + " " + array[lineCount][7] );
            formUtility.addLabel("Name Info: ", form);
            //JTextField
            nameInfo = new JTextField();
            Dimension nameInfoSize = nameInfo.getPreferredSize();
            nameInfoSize.width = 180;
            nameInfo.setPreferredSize(nameInfoSize);
            JPanel nameInfoPanel = new JPanel();
            nameInfoPanel.setLayout(new BorderLayout());
            nameInfoPanel.add(nameInfo, BorderLayout.WEST);
            formUtility.addLastField(nameInfoPanel, form);
            nameInfo.setText(getNameInfo(array, lineCount));
            formUtility.addLabel("Last Name: ", form);
            //JTextField
            lname = new JTextField();
            Dimension lnameSize = lname.getPreferredSize();
            lnameSize.width = 150;
            lname.setPreferredSize(lnameSize);
            JPanel lnamePanel = new JPanel();
            lnamePanel.setLayout(new BorderLayout());
            lnamePanel.add(lname, BorderLayout.WEST);
            formUtility.addLastField(lnamePanel, form);
            //lname.setText("xxx");
            formUtility.addLabel("First Name: ", form);
            //JTextField
            fname = new JTextField();
            Dimension fnameSize = lname.getPreferredSize();
            fnameSize.width = 150;
            fname.setPreferredSize(fnameSize);
            JPanel fnamePanel = new JPanel();
            fnamePanel.setLayout(new BorderLayout());
            fnamePanel.add(fname, BorderLayout.WEST);
            formUtility.addLastField(fnamePanel, form);       
            formUtility.addLabel("Middle Initial: ", form);
            //JTextField
            mname = new JTextField();
            Dimension mnameSize = mname.getPreferredSize();
            mnameSize.width = 20;
            mname.setPreferredSize(mnameSize);
            JPanel mnamePanel = new JPanel();
            mnamePanel.setLayout(new BorderLayout());
            mnamePanel.add(mname, BorderLayout.WEST);
            formUtility.addLastField(mnamePanel, form);   
            formUtility.addLabel("Facility: ", form);
            //JTextField spacer = new JTextField();
            //Dimension spacerSize = spacer.getPreferredSize();
            //spacerSize.width = 20;
            //spacer.setPreferredSize(spacerSize);
            JPanel spacerPanel = new JPanel();
            spacerPanel.setLayout(new BorderLayout());
            //spacerPanel.add(spacer, BorderLayout.WEST);
            formUtility.addLastField(spacerPanel, form);   
         //Container contentpane;
            //contentpane = getContentPane();
         //contentpane.setLayout(new FlowLayout());
            final JList list = new JList(SenListArraySetUp.facilities);
            /* getFacilityIndex( SenListHelpers.getFacility(array, lineCount), facilities ) */
            System.out.println("getFacility     " + SenListHelpers.getFacility(array, lineCount) );
            System.out.println("*******");
            //System.out.println("getFacility     " + getFacilityIndex( SenListHelpers.getFacility(array, lineCount), SenListArraySetUp.facilities ) );
            //getFacilityIndex( SenListHelpers.getFacility(array, lineCount), facilities );
            System.out.println(" ");
            int index = getFacilityIndex( SenListHelpers.getFacility(array, lineCount), SenListArraySetUp.facilities );
            System.out.println("Index    " + index);
         list.setSelectedIndex(0);
            list.setVisibleRowCount(1);
         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         //contentpane
            spacerPanel.add(new JScrollPane(list));
            formUtility.addLabel("Seniority Date: ", form);
            //JTextField
            sdate = new JTextField();
            Dimension sdateSize = sdate.getPreferredSize();
            sdateSize.width = 70;
            sdate.setPreferredSize(sdateSize);
            JPanel sdatePanel = new JPanel();
            sdatePanel.setLayout(new BorderLayout());
            sdatePanel.add(sdate, BorderLayout.WEST);
            formUtility.addLastField(sdatePanel, form); 
            sdate.setText(array[lineCount][SenListHelpers.getSenDateIndex(array, lineCount)]);
            formUtility.addLabel("Score: ", form);
            JTextField score = new JTextField();
            Dimension scoreSize = score.getPreferredSize();
            scoreSize.width = 20;
            score.setPreferredSize(scoreSize);
            JPanel scorePanel = new JPanel();
            scorePanel.setLayout(new BorderLayout());
            scorePanel.add(score, BorderLayout.WEST);
            formUtility.addLastField(scorePanel, form);       
            formUtility.addLabel("Score: ", form);
            //JTextField
            score = new JTextField();
            Dimension scoreSize = score.getPreferredSize();
            scoreSize.width = 30;
            score.setPreferredSize(scoreSize);
            JPanel scorePanel = new JPanel();
            scorePanel.setLayout(new BorderLayout());
            scorePanel.add(score, BorderLayout.WEST);
            formUtility.addLastField(scorePanel, form); 
            score.setText(array[lineCount][SenListHelpers.getArrayColLength(array, lineCount)]);
            formUtility.addLabel("Scramble: ", form);
            //JTextField
            scramble = new JTextField();
            Dimension scrambleSize = scramble.getPreferredSize();
            scrambleSize.width = 30;
            scramble.setPreferredSize(scrambleSize);
            JPanel scramblePanel = new JPanel();
            scramblePanel.setLayout(new BorderLayout());
            scramblePanel.add(scramble, BorderLayout.WEST);
            formUtility.addLastField(scramblePanel, form);       
            JButton addButton = new JButton("Add");
            form.add(addButton);
            //addButton.add(       
         addButton.addActionListener(
              new ActionListener()
              public void actionPerformed( ActionEvent actionEvent )//valueChanged(ListSelectionEvent e)
                        System.out.println("LName is:    " + lname.getText());
                        System.out.println("FName is:    " + fname.getText());
                        System.out.println("MName is:    " + mname.getText());
                        System.out.println("Facility is: " + SenListArraySetUp.facilities[list.getSelectedIndex()]);
                        System.out.println("SenDate is:  " + sdate.getText());
                        System.out.println("Score is:    " + score.getText(/*SenListHelpers.getArrayColLength(array, lineCount - 1)*/));
                        System.out.println("Scramble is: " + scramble.getText(/*SenListHelpers.getArrayColLength(array, lineCount)*/));
                        nameInfoString = lname.getText()    + " " + fname.getText() + " " + mname.getText() + " " +
                                         SenListArraySetUp.facilities[list.getSelectedIndex()]
                                                            + " " + sdate.getText() + " " + score.getText() + " " +
                                         scramble.getText();
                        //System.out.println("Size is: " + SenListHelpers.getArrayLength(SenListArraySetUp.NYSDOCS_Alpha_List_LastNames));
                        insertMethods.insertIntoNYSDOCSAlphaHelper(
                           lname.getText(), fname.getText(), mname.getText(),     
                          facilities[list.getSelectedIndex()],               
                          sdate.getText(), score.getText(), scramble.getText() );
                        //form.cl
                        f.dispose();
                        JOptionPane.showMessageDialog(null, "The Officer has been Added.");
                        //return;                   
                        //System.exit(0);
                        //System.out.println("Facility is:    " + facilities[list.getSelectedIndex()]);
                        /**/ //System.out.println("Facility is:    " + facilities[list.getSelectedIndex()]);
                  //contentpane.setBackground(listColorValues
                        //[list.getSelectedIndex()]);
            // Add an little padding around the form
            form.setBorder(new EmptyBorder(2, 2, 2, 2));
    //        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//original close operation
            // Note that we don�t use pack() here, since that
            // may shrink the �last" column more than we want.
            f.setSize(300, 300);//230);
            f.setVisible(true);
            //return;
        }

  • I want to know when my servlet completes its execution

    sir, i want to exactly know when my servlet completes its exacution. is there any way to find the servlet completion time please help me.
    iam waiting for ur kind answer and suggestions......
    thanks in advance.

    kumaranramuvr wrote:
    sir, i want to exactly know when my servlet completes its exacution. Why would you like to know? Also, by "execution" do you only mean service(), doGet(), doPost() methods?
    As said by BalusC, service() method is executed for every incoming request. Based on the HTTP method of the incoming request (either POST or GET), either doPost() or doGet() are invoked.
    Also, servlet is multi-threaded, meaning, for every new request a new servlet thread is created to process that request, unless you are implementing SingleThreadModel interface.

  • Stop a method from executing until another class does its bit

    Hi all,
    For my app I have a login screen where to get login success the user must first register. I therefore have two class LoginDialog and Register which is a dialog.
    In LoginDialog if the user clicks on Register it brings up a new instance of the Register dialog but continues to process the calling method (which happens to return to another class processing the login). What I require is that when I create a new Register object, the creating method does nothing until the Registration form is completed. I'm not at all au fait with threads so was wondering if there is an easy way to do it.
    I have thought of passing the LoginDialog as an argument in the Register constructor and having an empty while loop running in the invoking method (i.e. while (false) do nothing) and creating public access to that boolean variable so that at completion of the registration it sets the boolean variable to true in LoginDialog so it should break out of the while loop and continue. Is that a satisfactory way of pausing and restarting a method?
    Cheers,
    Chris

    Hi,
    I have a MainFrame class which calls processLogin which creates a new LoginDialog which houses the Register button. When I click on the register button it opens a new Registration screen but LoginDialog returns to MainFrame in the background and says that no user has logged in. What I require is that when the Register object is created after clicking the Register button that LoginDialog waits until the Registration is complete.
    Maybie the code will help (sorry if it is a bit lengthy).
    Snippet of LoginDialog
    public void actionPerformed(ActionEvent event)
            if(event.getSource() == ok) {
                 _username = user.getText();
                   _password = new String(password.getPassword());
                   _server = server.getText();
                   //ensure port number is an integer
                   try{
                        _port = Integer.parseInt(port.getText());
                   catch(NumberFormatException e){
                        JOptionPane.showMessageDialog(this,
                        "Please use an integer value only for the port number","Error",
                        JOptionPane.WARNING_MESSAGE);
                   //checks username and password length
                   if((_username.length()==0) || (_password.length() == 0)){
                        JOptionPane.showMessageDialog(this,
                             "Please enter a valid username and password","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   //checks server length
                   if(_server.length()== 0){
                        JOptionPane.showMessageDialog(this,
                             "Invalid server host","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   try{
                        db = new DatabaseConnection();
                        boolean exists = db.doesUserExist(_username, _password);
                        db.close();
                        if(exists){
                             //System.out.println("User exists on database");
                             this.dispose(); //get rid of login screen now user is confirmed
                        if(!exists){
                                  _username = null;
                                  _password = null;
                                  this.dispose();
                   catch(java.sql.SQLException e){
                        JOptionPane.showMessageDialog(this,
                             "Unable to connect to database. Please try again.","Error",
                                  JOptionPane.WARNING_MESSAGE);
              else if(event.getSource() == cancel) {
                   //NOTHING
              else if(event.getSource() == register){
                   Register register = new Register();
                   //while (processRegistration){
              this.setVisible(false);
         }and Register
    //import classes
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JFrame implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFirstName;
         JLabel lblLastName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblEmail;
         JLabel lblSex;
         String userName;
         char[] userPwd;
         char[] cnfPwd;
         String strUserPwd;
         String strCnfUserPwd;
         String firstName;
         String lastName;
         String age;
         String empid;
         String email;
         String sexStr;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox comboSex;
         JTextField txtUserName;
         JPasswordField txtUserPwd;
         JPasswordField txtCnfUserPwd;
         JTextField txtFirstName;
         JTextField txtLastName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         DatabaseConnection db;
         boolean exists, entrySuccess;
         public Register() {
              this.setTitle("Register");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Registration Info");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUserPwd = new JPasswordField(15);
              panel.add(txtUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUserPwd=new JPasswordField(15);
              panel.add(txtCnfUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFirstName=new JLabel("First Name");
              panel.add(lblFirstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFirstName=new JTextField(15);
              panel.add(txtFirstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLastName=new JLabel("Last Name");
              panel.add(lblLastName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLastName=new JTextField(15);
              panel.add(txtLastName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sexArr = {"Male", "Female"};
              comboSex = new JComboBox(sexArr);
              comboSex.setSelectedIndex(0);
              panel.add(comboSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setVisible(true);
              setSize(450,400);
         }//end or Register()
         public void actionPerformed(ActionEvent ae) {
              Object o = ae.getSource(); //get the source of the event
              if(o == btnCancel)
                   this.dispose();
              if(o == btnSubmit){
                   userName = txtUserName.getText();
                   userPwd = txtUserPwd.getPassword();
                   strUserPwd = new String(userPwd);
                   cnfPwd = txtCnfUserPwd.getPassword();
                   strCnfUserPwd = new String(cnfPwd);
                   firstName = txtFirstName.getText();
                   lastName = txtLastName.getText();
                   age = txtAge.getText();
                   empid = txtEmpId.getText();
                   email = txtEmail.getText();
                   sexStr = (String)comboSex.getItemAt(0);
                   db = new DatabaseConnection();
                   //Now check to see if username and password combination have been
                   //taken
                   try{
                        exists = db.doesUserExist(userName.trim(), strUserPwd.trim());
                   catch (java.sql.SQLException e){
                        System.out.println(e);
                   //Checks that each field has been filled in.
                   if(userName.length() == 0 ||  strUserPwd.length() == 0 ||
                   strCnfUserPwd.length() == 0 || firstName.length() == 0 ||
                   lastName.length() == 0 || age.length() == 0 || empid.length() == 0
                   || email.length() == 0){
                        JOptionPane.showMessageDialog(this,
                        "One or more entry has not been filled in. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);     
                   //Ensures that passwords match
                   if(!strUserPwd.equals(strCnfUserPwd)){
                        JOptionPane.showMessageDialog(this,
                        "Passwords do not match. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(exists){
                        JOptionPane.showMessageDialog(this,
                        "Username and password combination already exists. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(!exists) {
                        String userDetails = (userName.trim() + " " + strUserPwd.trim()
                        + " "  + firstName.trim() + " "
                        + lastName.trim() + " " + age.trim() + " " + empid.trim() + " "
                        + email.trim() + " " + sexStr.trim());
                        //System.out.println(userDetails);
                        //Try to connect to the database and insert the user details.
                        //If successful then user will be alerted and the registration page
                        //should be disposed automatically. If for some reason the insert
                        //was not successful then user is prompted to try again.
                        try{
                             entrySuccess = db.registerUser(userDetails);
                             if(entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "Congratulations, you have successfully registered for the Instant Messenger service!",
                                  "Message", JOptionPane.INFORMATION_MESSAGE);
                                  this.dispose();     
                             if(!entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "There was a problem entering your details. Please try again.",
                                  "Message", JOptionPane.ERROR_MESSAGE);
                        catch(java.sql.SQLException e){
              }//end of else
              db.close();
         }//end of actionPerformed()
    }//end of classCheers,
    Chris

  • Before the selector value reach a Case structure I need to stop it until a push button is pressed. How to do?

    Before the selector value reach a Case structure I need to stop it until a push button is pressed. How to do?

    altenbach wrote:
    UliB wrote:
    simply wire your selector value through a while loop. Stop the loop with your button. After the loop stops, the value will go on to the case structure.
    Hmmmm.....
    Hello altenbach,
    roflol .
    Thank you for the link to 'A Field Guide To LabVIEW Objects - Selfish Loop'. I'll keep that in mind, when answering other questions with while loops.
    Uli

  • How to start a thread after the execution/termination of another thread.???

    Hello,
    How to start a thread after the execution/termination of another thread....???
    For example:
    consider two threads: ThreadA and ThreadB
    I could start the ThreadB after the execution of ThreadA.
    How to identify the termination of one thread.....???
    Please help me...
    Thanks & Regards,
    Kayalvizhi

    What do you mean with "it doesn't work"? Do you get a compiler error? Do you get an exception at runtime? What's the error message?
    Jesper

  • Update JFrame via another Thread

    Hello,
    I have a JFrame with a JProgressBar, and I need to see the JProgressBar fill as some operation executes. In that JFrame there's a public method that increments the JProgressBar. This serves as a GUI to another class. That other class receives, as an argument, the JFrame, in order to be able to call that public method to increment the JProgressBar.
    Something like:
    public class Worker{
       public Worker(JFrame jf){
          this.frame = jf;
       public doWork(){
          instruction1;
          frame.updateProgressBar();
          instruction2;
          frame.updateProgressBar();
    }This has a major problem: the JFrame's graphics won't be updated (you won't see the progress bar filling during the operation). So I made a class to run the Worker on a Thread, that looks something like:
    public class WorkerThread extends Thread{
       public WorkerThread (Worker w){
          this.worker= w;
       public void run(){
          w.doWork();    
    }This got the problem solved, the JProgressBar is now correctly updated. But it created a new problem: I need the JFrame to wait for the WorkerThread to finish, and that's what I'm having real trouble with:
    public class GUI extends JFrame{
       private worker = new Worker();
       void someButtonPressed(...){
          WorkerThread wt = new WorkerThread(worker);
          wt.start();
          System.out.println("I don't want to see this until the Thread finishes");
    }If I leave this as is, I'll see the text before the Thread finishes.
    So I added "wait()" between the last two instructions, and a "notify()" as the last instruction of the run() method on WorkerThread. Unfortunately, this gives me two exceptions (java.lang.IllegalMonitorStateException: current thread not owner), one when I call wait() and another when I call notify(). If I make the two methods that call wait() and notify() synchronized, the JFrame's graphics won't update correctly (back to the initial problem).
    Any suggestions? Sorry for the long post, and thanx in advance! :)

    I don't really understand why you are using two JFrames.
    Typically in an application you have a single main JFrame. Whenever you need additional information you would create and display a "modal" JDialog. A modal JDialog prevents the JFrame from receiving any events. So in your example the progress bar should be added the dialog. When the long running task is finished you close the dialog an execution continues back in your main JFrame.

  • Delaying execution until a specified time

    All,
    I am developing a web application using Java servlets (no JSPs). What I have been trying to accomplish is to pass a date in a specified format to a servlet, have the servlet parse the date, and then upon that specified date complete its actions. The passing of the date and parsing works fine, and I can actually get the difference between the specified date and the current date and execute a Thread.currentThread().sleep(difference), but this only seems logical for dateTimes that are fairly close to the current dateTime. This method would obviously not be useful if one wanted to send a date three months from now to this servlet. My question therefore is, Is there a better way to accomplish this?

    Thank you so much for your reply, and I am sorry that this reply has taken me so long. I believe that this will work, but it essentially has the same issue of as I am facing in that it would not be very useful in scheduling a task three months from any given date, because internally it uses the Object.wait(long) method for a given Thread. This would mean, if i am thinking correctly, that my servlet would have to be executed in a browser that would need to be open constantly until execution (three months)? If this is not the case, then please correct me. OItherwise, I may have to take this particular functionality out of a servlet and place it in a stand alone app.

  • Catching an exception thrown from another thread

    I have a SocketServer that creates new threads to handle incoming clients. If one of the threads throw a SQLException is it possible to catch that exception in the SocketServer that created that thread.
    I tried implementing this code and I cannot get the server to catch an exception thrown in the thread. Are my assumptions correct?
    I was reading something about Thread Groups and implementing an uncoughtException() method, but this looked like overkill.
    Thanks for your time!
    Some Example code would be the following where the ClientThread will do a database query which could cause an SQLException. I'd like to catch that exception in my Socket Server
          try
                 new ClientThread( socketServer.accept() , host, connection ).start();
          catch( SQLException e )
                 System.out.println( "DataSource Connection Problem" );
                  e.printStackTrace();
          }

    hehe, why?
    The server's job is to listen for an incoming message from a client and pass it off to a thread to handle the client. Otherwise the server will have to block on that incoming port untill it has finished handling the client and usually there are many incoming clients continuously.
    The reason I would want to catch an exception in the server based on the SQLException thrown in the thread is because the SQLException is usually going to be due to the fact the datasource connection has become unavalable, or needs to be refreshed. This datasource connection is a private variable stored in the socket server. The SocketServer now needs to know that it has to refresh that datasource connection. I would normally try to use somesort of flag to set the variable but to throw another wrench into my dilemma, the SocketServer is actually its own thread. So I can't make any of these variables static, which means I can't have the thread call a method on teh socket server to change the status flag. :)
    I guess I need implement some sort of Listener that the thread can notify when a datasource connection goes down?
    Thanks for the help so far, I figured java would not want one thread to catch another thread's exceptions, but I just wanted to make sure.

  • Running another thread not to block UI

    I do some heavy operation inside the actionPerformed (load images from File Chooser, resize it for display and populate it in the ScrollPane etc) and I realize that the windows freezes until the whole operation is finished. And it doesn't really help that I do repaint() or validate(). I make some research and some of the books and people from forums say that I actually needed to dispatch another thread to run the heavy operation. So that I won't block the UI interface and can update things accordingly. But the problem is, I don't have any clear example to understand this concept. How to clean up the thread after operation finished. How can a thread notify the progress back and etc. I need to know how much images has been loaded so that I can update the progress bar and so on. Can anyone help me point out a good example? :D

    Think I should show my code snippet to you
    public void actionPerformed(ActionEvent e) {
            if (e.getSource() == BtnBrowse) {
                int returnVal = fcSelectFile.showDialog(this,"Select");
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file= fcSelectFile.getSelectedFiles();
                    //This is where a real application would open the file.
                    Thread worker=new Thread(){
                            public void run(){
                                int count=0;
                                selectedFile=new JLabel[file.length]; 
                                while(count<file.length)
                                {   final int index=count;
                                    String actualFile=file[count].toString();
                                    String fileName= file[count].getName();
                                    selectedFile[count]=new JLabel(createImageIcon(actualFile,fileName));
                                    SwingUtilities.invokeLater(new Runnable(){
                                    public void run(){
                                    PnlImageHolder.add(selectedFile[index]);
                                    PnlImageHolder.repaint();
                                    PnlImageHolder.validate();
                                    count++;
                    worker.start();
                    ScpImageScroller.getViewport().add(PnlImageHolder);
    }

  • Shutting down a panel in one thread from another thread.

    For various reasons, I have a program with two threads (actually more than two, but only two are concerned here). One is the main panel that runs at startup, another is a Virtual O'Scope panel with a real-time display. Everything works more or less well, until it's time to exit the program.
    The main program starts by calling a routine to display the VO'scope; this routine calls CmtScheduleThreadPoolFunctionAdv to schedule the VOscope thread with the function VOscopePanelMain.
    VOscopePanelMain initializes things, displays the VOscope panel, and then calls RunUserInterface(); to process events in the VOscope panel.
    When it comes time to close the window, closing the panel (the X box in the upper right corner) triggers the panel callback CB_VoscopePanel, which processes the EVENT_CLOSE: event by calling QuitUserInterface(0); which, in turn, causes RunUserInterface to return to VOscopePanelMain, which then shuts things down, closes the panel properly, and exits. So far so good.
    int CVICALLBACK CB_VoscopePanel (int panel, int event, void *callbackData,
            int eventData1, int eventData2)
        int    iPanelHeight, iPanelWidth, iV2ControlLeft, iV2ControlWidth, iWidth,
            iT2ControlTop, iT2ControlHeight, iHeight, iLeft, iGap, iScreenTop, iScreenLeft,
            iTop, iBoxWidth;
        switch (event) {
            break;
        case EVENT_GOT_FOCUS: //happens when first displayed or refreshed
        case EVENT_PANEL_SIZE: //size the controls on the panel
           ... do stuff here;
            break;
        case EVENT_CLOSE:
            QuitUserInterface(0);  //stop VOscopePanelMain, which in turn closes the panel and cleans stuff up.
            break;
        return 0;
    However, I also want the panel to stop when I close the main program. The only way that I know how to do this cleanly is to have the main program (which has closed all of its panels and is in the process of shutting down) call VOSCOPE_Close_VOScope () which, in turn, calls CallPanelCallback (iHandle_VOscope, EVENT_CLOSE, 0, 0, 0); (which forces a call to CB_VoscopePanel above with the EVENT_CLOSE event), which should call QuitUserInterface, which should cause the RunUserInterface in VOscopePanelMain to return and let it continue to shut down. In addition, after calling CallPanelCallback, the shutdown routine calls CmtWaitForThreadPoolFunctionCompletion to wait for the VOscopePanelMain thread to actually quit and clean up before proceeding.
    But, of course, it doesn't since, and it took me a while to realize this. The call to QuitUserInterface isn't coming from inside of the VOscopePanelMain thread, it's coming from the main panel's thread - which is already in the process of shutting down. So, the main panel thread is telling itself to quit, VOscopePanelMain never gets the QuitUserInterface message, and things stall.
    So: how do I have one thread tell a panel in another thread to cleanly close? Or do I have to get complicated and either replace RunUserInterface in VOscopePanelMain with a loop that processes events manually and looks for a flag, or figure out something with a thread-safe queue? Any help appreciated.
    Attachments:
    Voscope.c ‏76 KB

    Sorry for delay in answering, it took me a while to find time to build up a working example.
    The attached program spawns a thread in a new thread pool and permit you to choose whether to close it from the main thread or the spawned thread itself.
    It appears that in such a minimal configuration the process works as expected. There may be some different configuration in your actual program that prevents this.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    ThreadPoolWithGUI.zip ‏7 KB

  • Breaking a Program Execution into Multiple Threads

    Hi,
    We want to run a BAPI with Differenet parameters synchronoulsy in the same program as the BAPI is taking a very lon time for execution.
    We are Planning to break up the execution and the call o the BAPI into multiple threads that can run synchronously. How can this concept implemented in SAP ABAP.
    Thanks in advance.
    Arunava

    I am using parallel processing in my current client. Basis define a dialog processes group that we can use. This way our program will be limited to the number of processing give in the group. For example, our production system has 5 servers and each servers has 15 dialog processes. Basis reserve in the group 5 dialog processes for each group. So when we run our program, we are limited to 25 processes. We use function module SPT_INITIALIZE to find out the number of dialog processes and free processes for our group.
    The logic of the program as follow:
    Do loop
        Call function module with starting new task and destination in group performing end of task subroutine
    Enddo
    Wait until all task completed (check help on wait-you need to keep track of the number of record completed)
    In end of task subroutine, use command receive results from function to get the return parameters.
    Hope this helps.
    Cheers

  • Killing an exec'ed process from another thread

    Hi all,
    I written an application that executes some external OS - processes. There is a dispatcher thread, that starts the execution threads for some jobs. Every execution thread creates a Processes by calling runtime.exec(), adds this object to a TreeMap ( member of the dispatcher ), creates two threads for reading the output of the process ( sdtout & stderr ) and calls p.waitFor(). From this moment this thread is blocked. After the process is done, the results will be processed by this thread etc. Now I want to go ahead and let the application user kill the process. For them I let the dispatcher - thread, that has also a reference to the executed process to call destroy of it if necessary during the execution thread is blocked by waitFor() and two output threads are reading stdout & stderr. The problem is however that destroy() - call from another thread doesn't kill the subprocess. The subprocess is running until it's done or terminated from out of jvm. Have you an idea or example?
    Thanks a lot & regards
    Alex

    >
    I know you have been discussing your problem is that
    you can't kill a "sleep" process. But just to be
    sure, I tested your description by one thread exec-ing
    a "not-sleep" program, and then another thread had no
    trouble killing it.
    I took your code and wrote a program around it such
    that
    Thread1 :
    - creates a Job (but not a "sleep" job); creates a
    JobMap ; puts Job in JobMap
    - starts Thread2 (passing it JobMap)
    - sleeps 15 seconds
    - calls Job.kill() (your method)
    Thread2 :
    - gets Job from JobMap
    - calls Job.execute() (your method)
    It's quick and dirty and sloppy, but it works. The
    result is when the kill takes place, the execute
    method (Thread2) wakes from its waitFor, and gets
    exitValue() = 1 for the Process.
    so,
    In order to kill the sleep process, which (according
    to BIJ) is not the Process that you have from exec
    call, maybe the only way to kill it is to get its PID
    an exec a "kill -9" on it, same as you said you had to
    do from the commandline. I don't know if you can get
    the PID, maybe you can get the exec-ed process to spit
    it onto stdout or stderr?
    (I am on win, not *nix, right now, so I am just
    throwing out a suggestion before bowing out of this
    discussion.)
    /MelHi Mel,
    yes, it should work right on windows because you created probably the shell by cmd /c or something like this. If you kill the cmd - process, everithing executed by the interpretter will be killed too. My application is running on Windows and unix. On unix I have to execute the process from a shell ( in my case it is the born shell ). The problem is however, that the born shell has another behaviour as cmd and doesn't die. Do you have an idea how to get the pid of the process started by sh without command line? To kill the processes from the command line is exactly what my customers do now. But they want to get "a better service" ...:-)
    Regards
    Alex

  • Mail in queue stuck until another message is sent

    Hi all,
    I have postfix running nicely. However periodically a message get stuck in the mail queue and does not get sent until:
    1) the mail service is restarted
    2) another message is sent and this seems to ‘flush’ it out.
    Is there a configuration option to get this mail flushed out automatically?
    Many thanks

    I have postfix running nicely. However periodically a
    message get stuck in the mail queue and does not get
    sent until:
    1) the mail service is restarted
    2) another message is sent and this seems to ‘flush’
    it out.
    I am having the exact same problem. Here are the steps I've taken so far:
    1) Edited /etc/hostconfig to enable the postfix daemon: MAILSERVER=-YES- (was MAILSERVER=-AUTOMATIC-)
    2) Edited /etc/postfix/master.cf to set a wakeup time of 60 seconds for the pickup and qmgr services
    3) Enabled verbose logging by adding a '-vvv' flag in master.cf after pickup, cleanup, qmgr, flush, smtp, relay, showq, error, local, and lmtp.
    4) Enabled verbose by adding a '-vvv' flag in /System/Library/StartupItems/Postfix/Postfix, resulting in "/usr/sbin/postfix -vvv start"
    5) Restarted postfix using "postfix stop; postfix -vvv start" as root
    I am using the "sendmail" program from a CGI script to send email. The message goes into the maildrop directory and sometimes it is delivered, but other times it is stuck in the queue for an unbounded length of time (not until another message is submitted or postfix is restarted).
    This looks identical to the complaints on the thread below, but I'd rather not have to compile and replace postfix to fix this problem:
    http://groups.google.com/group/list.postfix.users/browse_thread/thread/26eb7a0ef b126bb5/fa38a2da8786e668?tvc=2&q=osx+queue#fa38a2da8786e668
    It appears that sendmail (and/or postdrop) is not reliably signaling the pickup daemon and the periodic wakeup is not causing pickup to scan the maildrop directory.
    I have tons of logs, but I don't want to post it all here. Please let me know what would be relevant and I will post.
    Thanks in advance.
    PowerBook G4   Mac OS X (10.3.9)  

  • Starting and stopping a VI from another VI

    Hello
    I have to write a VI for starting and stopping a vi from another vi. I browsed the forums for an example but couldn't find one. If anyone has an example it would be of great help.
    Thanks
    Ankit

    I may be throwing myself into a pot of boiling water here, but...
    I don't think this method is called dynamically calling a VI. Going through the LabVIEW help says this about dynamically called VIs
    "You can dynamically load VIs instead of using statically linked subVI calls. A statically linked subVI is one you place directly on the block diagram of a caller VI. It loads at the same time the caller VI loads.
    Unlike statically linked subVIs, dynamically loaded VIs do not load until the caller VI loads them with the Open VI Reference. If you have a large caller VI, you can save load time and memory by dynamically loading the VI because the VI does not load until the caller VI needs it, and you can release it from memory after the operation completes. You also can use the VI Call Configuration dialog box to configure when to load the subVI."
    and:
    "Create a strictly typed VI reference to dynamically call a VI using the Call by Reference Node. The strictly typed VI refnum identifies the connector pane of the VI you are calling."
    It seems that the advantage of dynamically calling a VI you can call DIFFERENT VI's with the same function on the block diagram as long as both are strictly typed to have the same connector pane. So say you have a VI that has a voltage input and a time input and calculates the rate of voltage change, could be replaced by a VI that takes the same inputs, but does something else with the data. And both VI's could be called by the same function depending of the reference passed to "Call by Reference."
    I think the method of calling a VI and not caring about when it finishes is just an Invoke Node method.

Maybe you are looking for