Using threads

I'm trying to add a interminate progress bar to my app. I'll be connecting to a database to get information and store it into an ArrayList. Here is what I currently have:
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.*;
public class MusicList extends javax.swing.JPanel
    /** Creates new form MusicList */
    public MusicList ()
        initComponents ();
    /** Removed generated code **/
    static ArrayList al = new ArrayList();   
    public static JDialog dialog = null;
    public void main ( String arrgs[] )
        Connect connect = new Connect();
        showInDialog(this);
    public static Frame getFrame (Component comp)
        while(comp!=null && !(comp instanceof Frame))
            comp=comp.getParent ();
        return (Frame)comp;
    public void showInDialog (Component comp)
        dialog = new JDialog (getFrame (comp), "Connection Status");
        dialog.getContentPane ().add (BorderLayout.CENTER, this);
        dialog.pack ();
        dialog.setLocationRelativeTo (comp);
        dialog.setModal (true);
        dialog.setVisible (true);
class Connect extends Thread
    Connect()
        start();
    public void run()
        connect();
    private static void connect ()
        try
            MusicList.progressLabel.setText ("Connecting to database...");
            Connection connection = Database.sqlConnection ();
            MusicList.progressLabel.setText ("Downloading library list...");
            Statement stmt = connection.createStatement ();
            String sql = "SELECT * FROM audio";
            PreparedStatement pstmt = connection.prepareStatement (sql);
            ResultSet rs = pstmt.executeQuery ();
            while (rs.next ())
                MusicList.al.add (rs.getInt ("id") + "|" + rs.getString ("artist") + "|" + rs.getString ("title") + "|" + rs.getString ("path") + "|" + rs.getInt ("length"));
            Database.closeResultSet (rs);
            Database.closePreparedStatement (pstmt);
            Database.closeStatement (stmt);
            MusicList.progressLabel.setText ("Completing...");
            Database.closeConnection (connection);
        catch (SQLException e)
            // Could not connect to the database
            JOptionPane.showMessageDialog (null,"Unable to connect to the database.\n\nPlease check your network connection."
                    + "Contact the administrator if the problem persists.", "Connection Error",
                    JOptionPane.ERROR_MESSAGE);
            System.out.println ("Error: " + e.getMessage ());
}When it runs, the progress bar goes back and forth like it should, but nothing else executes. I used this as my guideline: http://data.uta.edu/~ramesh/help/JavaThreads-howto.html

Yeh, I honestly have no idea. I'm not sure where to
begin which is why I used the code from that site I
linked to and just changed the names to my classes
and methods.
The stuff is static because if it isn't, I keep
getting errors that I'm referencing a non-static
variable within a static method and such. If I had
'public static void main' and then
'showInDialog(this);' inside it, I get errors:
Compiling 1 source file to /home/tristan/Java
Programs/AudioStreamApp/build/classes
/home/tristan/Java
Programs/AudioStreamApp/src/MusicList.java:74:
non-static variable this cannot be referenced from a
static context
showInDialog(this);
istan/Java
Programs/AudioStreamApp/src/MusicList.java:74:
non-static method showInDialog(java.awt.Component)
cannot be referenced from a static context
showInDialog(this);
ome/tristan/Java
Programs/AudioStreamApp/src/MusicList.java uses
unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
My reply to that is: you are way in over your head.
Start with a smaller program, this is too complicated for you at this time.
Read about instance and class members here:
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
Message was edited by:
dwg

Similar Messages

  • Using threads in a process of two or more tasks concurrently?

    Dear,
    I need to develop through a Java application in a process that allows the same process using Threads on two or more tasks can be executed concurrently. The goal is to optimize the runtime of a program.
    Then, through a program, display the behavior of a producer and two consumers at runtime!
    Below is the code and problem description.
    Could anyone help me on this issue?
    Sincerely,
    Sérgio Pitta
    The producer-consumer problem
    Known as the problem of limited buffer. The two processes share a common buffer of fixed size. One, the producer puts information into the buffer and the other the consumer to pull off.
    The problem arises when the producer wants to put a new item in the buffer, but it is already full. The solution is to put the producer to sleep and wake it up only when the consumer to remove one or more items. Likewise, if the consumer wants to remove an item from the buffer and realize that it is empty, he will sleep until the producer put something in the buffer and awake.
    To keep track of the number of items in the buffer, we need a variable, "count". If the maximum number of items that may contain the buffer is N, the producer code first checks whether the value of the variable "count" is N. If the producer sleep, otherwise, the producer adds an item and increment the variable "count".
    The consumer code is similar: first checks if the value of the variable "count" is 0. If so, go to sleep if not zero, removes an item and decreases the counter by one. Each case also tests whether the other should be agreed and, if so, awakens. The code for both producer and consumer, is shown in the code below:
    #define N 100                     / * number of posts in the buffer * /
    int count = 0,                     / * number of items in buffer * /
    void producer(void)
    int item;
    while (TRUE) {                    / * number of items in buffer * /
    produce_item item = ()           / * generates the next item * /
    if (count == N) sleep ()           / * if the buffer is full, go to sleep * /
    insert_item (item)                / * put an item in the buffer * /
    count = count + 1                / * increment the count of items in buffer * /
    if (count == 1) wakeup (consumer);      / * buffer empty? * /
    void consumer(void)
    int item;
    while (TRUE) {                    / * repeat forever * /
    if (count == 0) sleep ()           / * if the buffer is full, go to sleep * /
    remove_item item = ()           / * generates the next item * /
    count = count - 1                / * decrement a counter of items in buffer * /
    if (count == N - 1) wakeup (producer)      / * buffer empty? * /
    consume_item (item)      / * print the item * /
    To express system calls such as sleep and wakeup in C, they are shown how to call library routines. They are not part of standard C library, but presumably would be available on any system that actually have those system calls. Procedures "insert_item and remove_item" which are not shown, they register themselves on the insertion and removal of the item buffer.
    Now back to the race condition. It can occur because the variable "count" unfettered access. Could the following scenario occurs: the buffer is empty and the consumer just read the variable "count" to check if its value is 0. In that instant, the scheduler decides to stop running temporarily and the consumer starting to run the producer. The producer inserts an item in the buffer, increment the variable "count" and realizes that its value is now 1. Inferring the value of "count" was 0 and that the consumer should go to bed, the producer calls "wakeup" to wake up the consumer.
    Unfortunately, the consumer is not logically asleep, so the signal is lost to agree. The next time the consumer to run, test the value of "count" previously read by him, shall verify that the value is 0, and sleep. Sooner or later the producer fills the whole buffer and also sleep. Both sleep forever.
    The essence of the problem is that you lose sending a signal to wake up a process that (still) not sleeping. If he were not lost, everything would work. A quick solution is to modify the rules, adding context to a "bit of waiting for the signal to wake up (wakeup waiting bit)." When a signal is sent to wake up a process that is still awake, this bit is turned on. Then, when the process trying to sleep, if the bit waiting for the signal to wake up is on, it will shut down, but the process will remain awake. The bit waiting for the signal to wake up is actually a piggy bank that holds signs of waking.
    Even the bit waiting for the signal to wake the nation have saved in this simple example, it is easy to think of cases with three or more cases in which a bit of waiting for the signal to wake up is insufficient. We could do another improvisation and add a second bit of waiting for the signal to wake up or maybe eight or 32 of them, but in principle, the problem still exists.

    user12284350 wrote:
    Hi!
    Thanks for the feedback!
    I need a program to provide through an interface with the user behavior of a producer and two consumers at runtime, using Threads!So hire somebody to write one.
    Or, if what you really mean is that you need to write such a program, as part of your course work, then write one.
    You can't just dump your requirements here and expect someone to do your work for you though. If this is your assignment, then you need to do it. If you get stuck, ask a specific question about the part that's giving you trouble. "How do I write a producer/consumer program?" is not a valid question.

  • Using threads to change button status

    Hi all
    im reworking my conway life adt and trying to build it into an ap (as i have it working as an applet)
    as applets have a repaint command then implementing the generations was pretty easy.
    However in an application i will have to use threads wont i?
    so what i have done is built an ap that builds the life grid using swing buttons (this isnt a swing question by the way its a thread question :p)
    so how would i go about threading my application so it doesnt freeze up?
    here is the code from my swing ap
    import javax.swing.*;
    import java.awt.*;
    public class LifeAp
    private Life gLife;
    private JButton[][] buttons;
    private JFrame frame;
         public LifeAp(int y, int x)
         gLife=new Life(y,x);
         buttons=new JButton[y][x];
         for (int yc=0;yc<y;yc++)
              for (int xc=0;xc<x;xc++)
                   JButton btn=new JButton();
                   btn.setBackground(new Color(204, 204, 204));
                   btn.setText("");
                   buttons[yc][xc]=btn;
         initLife();
         public void buildForm()
         frame = new JFrame("Life");
         frame.getContentPane().setLayout
               (new GridLayout(buttons[0].length,buttons.length));
         for (int y=0;y<buttons.length;y++)
              for (int x=0;x<buttons[0].length;x++)
                   frame.getContentPane().add(buttons[y][x]);
         frame.pack();
         public void setButtons()
         for (int y=0;y<buttons.length;y++)
              for (int x=0;x<buttons[0].length;x++)
                   if (gLife.getStatus(y,x)==0)
                        buttons[y][x].setBackground(new Color(204, 204, 204));
                   else
                        buttons[y][x].setBackground(new Color(255, 255, 0));
         public void initLife()
         buildForm();
         gLife.generateMap();
         setButtons();
         public void show()
         frame.setVisible(true);
         private void exitForm(java.awt.event.WindowEvent evt)
         System.exit(0);
         public static void main(String[] args)
         new LifeAp(16,16).show();
    }the form builds just fine.
    now in the Life adt i have a method called generation()
    so when i call gLife.generation(); the next life phase is calculated
    so i need in a thread to basically say
    gLife.generation();
    setButtons();which will update life then colour the buttons accordingly.
    however i think that maybe im going to hit problems because of static and non static methods etc.
    have i approached this the wrong way? or is this something quite easy to implement into a thread?

    ok so now i have
         public void start()
         animator = new Thread(this);
         animator.start();
         public void run()
         long tm = System.currentTimeMillis();
         while (Thread.currentThread() == animator)
              gLife.generation();
              setButtons();
              validate();
              show();
              try
                   tm += delay;
                   Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
              catch (InterruptedException e)
                   break;
              frame++;
         }and my current main is
         public static void main(String[] args)
         LifeAp l=new LifeAp(64,64);
         l.show();
         l.start();
         }what should i have in my main code to start my thread?
    if i have
    public static void main(String[] args)
         LifeAp l=new LifeAp(64,64);
         l.show();
         }then the process doesnt run, it just displays the first generation then stops.
    so what do i need to include?

  • I need a timer function to ping the server every 5 secs??using threads.

    I need a timer function to ping the server every 5 secs??
    using threads...i have to use a thread coz i cant use Timer and Timer Task coz clients r on the JDK1.2 version.I have created a thread which keeps checking th ping msg & any server msg is pings 4 the1st time properly but then it just waits to read the response from server but it doesnt but the server shows that it has send the msgs to client???PLEASE HELP URGENT

    Few things are not clear from your post, like, are you using sockets and if you are, how are u reading writing to them (ur sample code would help)...
    Anyways if you are, are you doing accept on your socket in a while(true) loop or just once... If you do it only once you will get the first ping message but none afterwards if the other side closes and opens new sockets for every send... What I am suggesting is something like the following:
    ss = new ServerSocket(port);
    while(true)
         s = ss.accept();
         is = s.getInputStream();
         os = s.getOutputStream();
         reader = new BufferedReader(new InputStreamReader(is));
         writer = new BufferedWriter(new OutputStreamWriter(os));
         String in = reader.readLine();
            // do something with this string
            s.close();
            // put some check here to break out of this infinite loop
    }// end of While

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • Using threads and collecting responses

    Hello,
    I am doing multiple requests to diferent web services from diferent providers. I want to do the requests simultaneously and I think the best way is using threads. I am thinking to create a main class that creates a thread instance for every request (max 5) and then wait for the responses with a timeout. What is best way to implement this? Is there any standard or typical strategy? Different points to consider are:
    - time out, the main class can't wait for ever the threads to end.
    - how every thread passes the response from de web service to the main class.
    Thanks in advance.

    Hi,
    best way to do this may be using an executor service. I cant describe this in detail here..basicly you have to create a executor
    ExecutorService executor = Executors.newCachedThreadPool();then you create so called "Callables" which are like Runnables, but return a result. There you implement your thread functionality in the "call" method.
    public class testCallable implements Callable{
              public Object call() throws Exception {
    }in your controlling class you add these to your executor service and assign the results to a Future (which is a nonblocking operation).
        // make a new Thread for each resouce
              Future[] futures = new Future[5];
              for (int i = 0; i < 5; i++) {
                   futures[i] = executor.submit(new testCallable());
              }then you retrive the result. You can assign a timeout there.
    try {
                 long timeoutTime = System.currentTimeMillis() + timeout;
              for (int i = 0; i < futures.length; i++) {
                   long remainingTime = Math.max(0, timeoutTime
                             - System.currentTimeMillis());
                   try {
                        Result result = (Result) futures.get(
                                  remainingTime, TimeUnit.MILLISECONDS);
    look at
    http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
    for details
    Greetings
    Brash

  • Using Threads And Sockets

    Hello,
    I want to create a program that can send 2 or more files through the socket to the same client at the same time. Is it possible? I am trying to use threads to do this but I am not sure what to do in those threads. Should I send the socket to the thread class and create BufferedReader and DataOutputStream again in the thread?
    Also should I create threads in the client-side?
    Thanks
    Edited by: bcaputcu on May 18, 2010 2:19 AM

    bcaputcu wrote:
    Hello,
    I want to create a program that can send 2 or more files through the socket to the same client at the same time. Is it possible?No. At least not in the way you're thinking.
    I am trying to use threads to do this but I am not sure what to do in those threads. Should I send the socket to the thread class and create BufferedReader and DataOutputStream again in the thread?No, because you can't do that. The socket won't create multiple streams for your threads.
    Also should I create threads in the client-side?No.
    You need to send the files one at a time. While you could basically send the data interleaved, it would still only involve only one thread, one socket and one set of streams. And it would be a silly thing to do.

  • Using threads in a jsp page

    I would like to know wether any one had used threads in a jsp page
    like one thread gets the data from database while other shows some text saying "getting data from database"
    Thank you

    "getting data from database" is not a valid message
    to give. You might think it's interesting, but the
    people using your application don't give a damn about
    you fetching something from the database.
    The basic rule is: people are stupid, don't give them
    any reason to be confused.Funny stuff, Ill remember that :-)

  • Using thread and socket connection with other machines

    Hi all!
    we are using weblgoic 5.1 SP9 JDK1.2.2
    we already using java.net.Socket and java.lang.Thread
    to communication TANDEM Machine on the weblogic.
    the reason why we use to socket and thread even though it is not
    recommanded is that below
    1. once we connect Socket, then we using until server shutdown or
    connection may has the problem, so we're using thread to wait
    java.io.Inputstream to read from socket.(if I using EJB, It can't
    wait socket inputstream indefinetly, because it has timeout)
    2. we're logging Database date sent or received with TANDEM Machine.
    so we need Database Access. so we using Database Access
    thru Weblogic.
    3. EJB Application using (other EJB Application - send Module)
    to send data to TANDEM Machine. So "Send Module" should
    be implemented EJB.
    but. Now I see there might be problem this framework.
    so, is there some way by just using J2EE spec, to implement this kind of
    framework.
    wait for your great help !!
    regards.

    Yes i've tried interrupt method and it doesn't have any effects on the thread... it stay in connect() method...
    And for the timeouts, in fact i use an API : J2SSH, to connect with SSH protocol, and the setting of connection timeouts is not implemented yet... and the default timeout is about 4 minutes...
    so i don't know how to solve this problem...

  • Using threads (SwingWorker) to update JTree component

    Hi,
    Im having a problem trying to update a JTree component (adding child nodes to an existing node) using threads. Im using the SwingWorker3 class (http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html) for threading.
    When the user selects a node for expansion, the logic for fetching the children of the selected node is executed under the construct() method of SwingWorker.
    Once this data is obtained, the job of adding the children to the selected node is done in the finished() method which runs on the event-dispatch thread as per documentation of SwingWorker3.
    The problem Im facing is that even though the data for the children is obtained and the finished() method executes and adds the children to the selected node, they are not visible in the UI.
    If anybody knows how this can be resolved, please let me know. Any help/pointers would be greatly appreciated.
    Rgds
    Sridhar

    I added the tree.updateUI() method call in the finished() method. This renders the children (Yipee!).
    But now I have a new problem. If I collapse and again expand a node, I get a NPE. (I see all the child nodes but a exception is still thrown) The exception happens after my treeWillExpand() and treeExpanded() method implementations. So no probs in my code.
    If you know of a solution, pleeease let me know.
    TIA
    Sridhar
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTreeUI.updateSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(Unknown Source)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  • Can we use threads in servlets

    Hi,
    can we use threads in servlets.
    cheers
    Sen

    You can also use java.io.Serializable at the end of you class
    eg:
    public class MyClass implements java.io.Serializable{

  • How to use threads in JSP???

    hello
    i want to use threads with JSP.
    i want to write a jsp page which will
    start 2 different threads. the 1st thread should just display a message and the second page should redirect this page to another jsp page.
    till the redirection is goin on, the message should be displayed in the browser from the 1st thread.
    i dont know actually how to use threads in JSP by implementing the Runnable insterface, if not m then how do i do it ??
    thanx
    Kamal Jai

    Why do you want to use threads to do this ??
    If you write a message and do a redirection, the message will be displayed until the other page will be loaded into the browser...
    I already launched a thread from a JSP but it was for a four hour process where the user can close his browser windows.

  • How to use Thread

    Hi,
    I am trying to write a program that does a background process. The process is controlled by two buttons: Start and Stop. I thought I'd use threads, but it does not work; the start button remains depressed and the user cannot click on the Stop button. The line calling run() is executed and execution transfers to the run method in my Thread subclass, which is wrapped in an infinite loop. The line after the run() method is never reached. It is as if it is not creating an extra thread at all.
    I have written something basic which is similar, the same problem occurs with this code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class CounterFrame extends JFrame {
        private JPanel pnButtons;
        private JButton btStart;
        private JButton btStop; 
        private ThreadTester threadtester;
        public CounterFrame() {
            pnButtons = new JPanel();
            btStart = new JButton("Start");
            btStop = new JButton("Stop");
            btStart.addActionListener(new StartListener());
            btStop.addActionListener(new StopListener());   
            pnButtons.add(btStart);
            pnButtons.add(btStop);
            add(pnButtons);
            pack();
            threadtester = new ThreadTester();
        private class StartListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                threadtester.run();
        private class StopListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                try {
                    threadtester.sleep(Long.MAX_VALUE);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        private class ThreadTester extends Thread {
            int counter;
            public ThreadTester() {
                counter = 0;
            public void run() {
                while(true) {
                    System.out.println(counter);
                    counter++;
                    try {
                        sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    yield();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new CounterFrame().setVisible(true);
    }Can anyone advise where I am going wrong, please?

    Please run, don't walk to the article on the Sun site (you can search for it) entitled Concurrency and Swing (or something similar). Problems I see include:
    1) Don't call run on a thread as that will just "run" the run method and not create a background thread. Instead you call "start".
    2) Don't call Thread.sleep() on the EDT or the Event Dispatch Thread. This is the single thread that Swing uses to draw components and to interact with the user. Calling Thread.sleep on it will put your whole program to sleep which is not what you want.
    3) Consider using a Swing Worker, or better still a Swing Timer.
    Again, read the article and you will understand this better.

  • How to use thread only for progress bar.....

    Hello,
    I am working on an application which is taking time to load. Now I want to use a progress bar to tell the user of the application that It is taking time to load. How to do it... I read the Java swing tutorial and went through the example. Please tell me what to do. Because I am unfamiliar with Threads and I am not using thread anywhere in my application.

    You are using threads. All Java execution occurs on threads. Write a Java GUI and you're in a multithreaded environment - there's no way out of that.
    If your "application is a complex one" then you would be better advised to understand threads than to try and pretend that they don't exist. For a start, if you don't think you're using threads then you're destined to run in to all sorts of problems as regards an unresponsive GUI, as you're probably now finding out.

  • How to use threads to reconnect a socket to a server in TCP/IP

    I want to know how to reconnect a socket to a server in TCP.
    Actually i wanted to do reconnection whenever a SocketException for broken connection etc. is thrown in my code. This I want to do for a prespecified number of times for reconnection in case of broken connection.When this number decrements to zero the program will exit printing some error message. I was planning to use threads by way of having some Exception Listeners but i am not sure How?
    Any suggestions will be really helpful..
    please help.
    Edited by: danish.ahmed.lnmiit on Jan 28, 2008 2:44 AM

    I want to know how to reconnect a socket to a server in TCP.There is no reconnect operation in TCP. You have to create a new Socket.

  • Retrieving records using Thread

    I am a newbie in Java Servlet programming. I want to retrieve some records from my db2 database every 5 minutes and then display the result for viewing.
    I have no idea where should I put my html tags. Assuming that my program only have 2 methods which are the doPost method and runningThread method, should I put the tags within the doPost method or inside the running thread?
    Example or tutorial are good in term of understanding for a beginner.
    Thanks in advanced for any help.

    You don't need to use threads to do it. If it is just updated response that you need, you can achieve it by setting headers appropriately for autorefresh.
    In your doPost method , call
    response.setIntHeader("Refresh", 300) the browser re-requests the page after 300 seconds
    Then you can pull the new data and display.
    HTH

Maybe you are looking for