Another thread question...

i am new to working with threads so i really appreciate the help,
anyways, i have a class where i want to launch a method as a thread. This
method takes 2 arguments, both Strings.
I can't come up with a good way to make sure that my method gets the right
parameters for each launch before they are overwritten by the next
incarnation of the primary thread.
     public synchronized void moveSingleFileThreaded(File FileBeingMoved, File FileWeAreMovingTo){
          currentMoveFromFile = FileBeingMoved;
          currentMoveToFile   = FileWeAreMovingTo;
          moverThread = new Thread(this,"Mover" + threadsCurrentlyRunning);
          moverThread.start();in the above code, i need to pass the 2 arguments into the method that will
be threaded. However, that method is called in run(), and since run takes no
arguments there is no way for me to pass them directly. In the above code i
assign the parameters to class data members. However, i am afraid that I
run
the risk of these data members being overwritten before I call this function
again. Am I too worried?
thanks

OK, that makes sense, and that was my first instinct
of what to do. However,
consider the following code:
public class A implements Runnable{
String INFO = null;
private Thread myThread = null;
public void A(String info){
INFO = info;
myThread = new Thread(this,"thread");
myThread.start();
}//end construct
public void run(){
String infoHolder = INFO;  //how can I make SURE
SURE SURE that infoHolder always gets the right
info?
//do something with infoHolder....
}//end class defI know that infoHolder is assigned the value of INFO
in the first line of the
thread, but can I be 100 percent sure this will
execute as expected everytime?
What happens if, for some crazy reason, the thread
gets bumped from
execution on the first line of the run() method, and
when it resumes the
constructor of this class has been called again, with
different info?
INFO and myThread are not static--each instance of "A" will have its own INFO value and its own myThread value. Calling the constructor creates a new instance of "A", so the original instance (that was suspended in your example) is not affected.
Then I
would have an erroneous thread once the original
thread is put back into
action.
The tricky part for me is the fact that I need some
of these threads to sleep
before execution (because I will be copying over a
network and don't want
to overload resources).
Any ideas? thanksAlso, initializing INFO and myThread to null is redundant--the JVM will do that automatically.

Similar Messages

  • Yet Another Thread Question

    Double-Checked Locking is used as an efficient method for implementing lazy initialisation in a multithreaded environment. Nevertheless some people think that it's a dangerous method. I would like to hear (read) your opinions.
    TIA

    Double-Checked Locking is used as an efficient method
    for implementing lazy initialisation in a
    multithreaded environment. Nevertheless some people
    think that it's a dangerous method. I would like to
    hear (read) your opinions.It is not dangerous as long as the whole team only uses acessors and never directly accesses the attributes. It depends on the programmer's discipline.

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • Thread questions

    Hi,
    Here are my Thread questions:
    Q.1 I don't understand interrupt() and internal flag and when should I use it?
    Q.2 What does "No thread can make another thread yield" mean?
    Q.3 Given:
    public class MyRunnable implements Runnable
         public void run()
              //some code here
    What is the proper way to create and start this thread?
    Ans: new Thread(new MyRunnable()).start();
    Why does it need to add new Thread as prefix?
    Q.4 Given:
    public class MyT extends Thread
         public void run()
              try
                   for(int i=1; i<5; i++)
                        System.out.print(i + " ");
                        if(i>2)
                        interrupt();
                        sleep(1000);
                        if(interrupted())
                        break;
              catch(InterruptedException e)
                   System.out.print("Caught");
    Assume another object creates an instance of this Thread and starts it. Why does the outcome is:
    1 2 3 caught
    Thanks
    gogo

    You can find a lot of answers to your questions in the java tutorial.
    http://java.sun.com/tutorial

  • Start timer from another thread

    I am working on a project which will receive command from telnet and start a timer.
    In the sock function, I use form reference to call timer.start(), but timer control cannot start Tick event:
    Here is code for sock functin after receive the command:
     static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
                switch (requestInfo.Key.ToUpper())
                    case ("START"):
                        session.Send(requestInfo.Body);
                        changetimer(1, requestInfo.Body);
    break;}}
    Here is the function to call timer start:
      static void changetimer(int action, string incomingmsg)
                //timer1.Start();
                Form1 frm = (Form1)Application.OpenForms["form1"];
                switch (action)
                    case 1:
                         frm.timer1.Start();
                         break;
                    case 2:
                        frm.timer1.Stop();
                        break;
    and this is timer tick :
    private void timer1_Tick(object sender, EventArgs e)
                TimeSpan result = TimeSpan.FromSeconds(second);
                string fromTimeString = result.ToString();
                label1.Text = fromTimeString;
                second = second + 1;

    You should start the timer on the UI thread. You could use the Invoke method to access a UI element from another thread:
    static void changetimer(int action, string incomingmsg)
    //timer1.Start();
    Form1 frm = (Form1)Application.OpenForms["form1"];
    switch (action)
    case 1:
    frm.Invoke(new Action(() => { frm.timer1.Start(); }));
    break;
    case 2:
    frm.Invoke(new Action(() => { frm.timer1.Stop(); }));
    break;
    Hope that helps.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Threads Question/Opinion

    I am currently developing an application that will create a process. The process itself will be cmd.exe with parameters. The application is Swing based and so I don't lock the event dispatch thread, I created a thread that will create the process. I also know that when using cmd.exe it is important to handle the inputstream and errorstream so the whole process does not lock. The examples I've seen for handling these streams where handled in threads of their own so they could be processed at the same time. My question is this: In your opinion would it be better to handle the process and streams in one thread, or should I create one thread to create the process and 2 threads to handle the streams (1 thread for each stream)? I think the multiple threads (essentially 3 for one process) will negatively impact the applications performance, but I don't know if handling the streams in a function/method within one thread would be adequate enough to keep the app from deadlocking. Any ideas?

    I had read that multiple threads can cause more
    e overhead and slow performance of the application in
    general. The article just said more threads=more
    overhead, Fair enough. That's true as far as it goes, but I can't imagine 3 threads ever causing any detectable problem, unless each thread is something like this public void run() {
        someField_++;
        Thread.yield();
    } It's not uncommon to have tens of threads, and I've created thousands in little dummy test programs and not noticed performance problems.
    I didn't have an exact number to work with
    and that was my concern. I believe the threads I was
    thinking of would perform the needed actions quickly
    and therefore not impact performance too much, but I
    wanted to be sure. The key is that each thead does enough at one time so that the overhead of switching is small compared to the work done, but also making sure that no thread hogs the CPU for too long. If you're doing I/O, then each call to read has the potential to let another thread have a turn, I believe. Otherwise it's common to put a call to yield in your thread's main loop. Maybe every iteration, maybe every 10 or 100 or whatever, depending on what that iteration does.
    If you have tasks that can be handled in parallel--indpendently of one another--or should be independent to prevent one from forcing another to wait (like reading two streams) then you should give those tasks separate threads. Once you have that working correctly, then if you have measured performance problems relating to how those threads interact or take turns (or don't take turns) then you can tweak the code to try to optimize that aspect of it.
    I am teaching myself Java and its
    been a bit of a haul. I appreciate the help and
    information I get from these forums hence this
    posting.Cool. Glad to be of help.

  • Can thread become a member of another thread  in Concurrent Programming

    i had this doubt in concurrrent programming,..........
    1)Can thread become a member of another thread in Concurrent Programming

    Threads are just objects that happen to have a special property:
    - when you invoke start() them the VM creates a new thread of execution to execute the Thread object's run() method
    A class that subclasses Thread is just a normal class and can have whatever members it like.
    Your questions don't make a lot of sense. If you are truly a "Novice in Java" then I recommend reading a few good books before you post in the forums.

  • Conceptual Thread question

    Good evening...
    i understand what multi-tasking and threading is.
    but what i'm having trouble with is the idea of having two threads communicate.
    for example a thread that reads several files simultaneously, and another thread that "requests" the most recent entry that was read from all the files.
    because it's not the entire object that runs in a separate thread right? it's really only the run() method, correct?
    thanks.
    so the run() method would have to do the work of reading the files and sorting what it reads, then stick it into a buffer where some other method of the object could return it when requested. is that the right way of thinking?

    Yes, something along those lines.
    Just because a Thread is running it doesn't prevent you from accessing its methods. Obviously attempting to call certain methods will throw IllegalStateExceptions and the like.
    If you want to get two Threads to communicate then you could either get one to regularly ask the other one questions, eg "do you have any more data for me?", or you could get one Thread to wait on the other Thread, thus only waking up when new data has arrived.
    In either case I would put some data buffer between them rather than actually within one of them.
    For example:
    public class ProducerThread extends Thread
      protected DataBuffer buffer;
      public ProducerThread(String filename, DataBuffer buffer)
        super("ProducerThread");
        this.buffer = buffer;
      public void run()
        try
          // Read in your data
          Iterator i = ...;
          while(i.hasNext())
            buffer.bufferData(i.next());
          buffer.setFinished(true);
        catch(Exception e)
          // Your exception handling
        finally
          // Close all your resources
    public class DataBuffer
      protected LinkedList dataList;
      protected boolean finished;
      public DataBuffer()
        dataList = new LinkedList();
        finished = false;
      public synchronized void bufferData(Object data)
        dataList.add(data);
        notifyAll(); // let anyone that's waiting for data know that some has arrived
      public synchronized Object waitForData() throws InterruptedException, IllegalStateException
        if(finished)
          throw new IllegalStateException("Buffer is finished");
        // If we can't return anything at this moment then get this thread to wait until another
        // thread puts something into the buffer
        if(dataList.empty())
          wait();
          if(dataList.empty()) // Usually caused by setFinished being called
            throw new IllegalStateException("Buffer is finished");
        return dataList.removeFirst();
      public boolean isFinished()
        return finished;
      public synchronized void setFinished(boolean finished)
        this.finished = finished;
        notifyAll(); // If someone's waiting then we should let them know that nothing's gonna happen
    public class ConsumerThread extends Thread
      protected DataBuffer buffer;
      public ConsumerThread(DataBuffer buffer)
        super("ConsumerThread");
        this.buffer = buffer;
      public void run()
        Object data;
        while(!buffer.isFinished())
          try
            data = buffer.waitForData();
          catch(Exception e)
            // Your exception handling code!
    }The code snippet uses synchronisation quite a bit to manage concurrent access to sensitive state.
    Just ask again if this doesn't make sense.
    Hope this helps.

  • Keymapping (follow up from another thread)

    To follow up on another thread, I checked out the keymappings and found most of what I was looking for.
    Only a couple of things I miss:
    1. SHIFT + TAB doesn't pull the text back with it if the text is not selected. I am convised most editors do this and I keep find myself trying to do it in JDev and it doesn't work, and then I go in a huff.
    2. Ctrl+K, Ctrl+L to perform a word match forwards or backwards, based purely on text in the document, ie. not syntax/context sensitive. This was one of my most used/most time saved features in Netbeans.

    Hi,
    don't understand what 1) is supposed to do. Can you explain this further? Winword and TextPad behave differently. I tried NetBeans and shift+tab is doing nothing.
    For 2) Is it the same as
    pressing ctrl+f to enter a search string and then continuing with F3 for forward matches and shift+F3 for backward matches? If you select a string before pressing ctrl+f then this string is added to the search list.
    If yes, then you can change the key mapping in Tools-->Preferences --> Accelerators to the keyboard combination you are most familiar with (look for "find").
    Frank

  • How to use ImageContr​ol on another thread out main

    Hi All,
    I'm looking to use ImageControl (ImageControl.fp) on another thread out main thread 
    In my second thread i try to update image but i have a error (This panel operation can be performed (if a top-level panel) only in the thread in which the panel was created, or (if a child panel) only in the thread in which the top-level parent panel was created.)
    Here my code
    Main thread :
    ImageControl_ConvertFromDecoration (panelHandle, PANEL_IMAGECTRL, 0);
    ImageControl_SetZoomToFit (panelHandle, PANEL_IMAGECTRL, 1);
    ImageControl_SetAttribute (panelHandle, PANEL_IMAGECTRL, ATTR_IMAGECTRL_SHOW_SCROLLBARS, 0);
     hdleThread = CreateThread(NULL, 0,  (LPTHREAD_START_ROUTINE) ThreadTest,  NULL,  0, &idThread);
    Secand thread :
    int ThreadTest (void * data)
    ImageControl_SetZoomToFit (panelHandle, PANEL_IMAGECTRL, 1);
    iIdError  =    ImageControl_SetAttribute (panelHandle, PANEL_IMAGECTRL, ATTR_IMAGECTRL_IMAGE, imageToDisplay);
    // iIdError  = -129
    Could you help me ?
    Thankyou

    many thanks.  I should have thought of the need for using the Target Display Mode. 
    tony

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • 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.

  • Are you suppose to access UIView from another thread?

    A lot of UI events in my apps take place in another thread. So in my uivewcontroller, it catches a button click for example, it launches a NSThread with some parameter. The reason I decided to use a thread is because if the duration takes long the UI completely locks up. The thread then fetches for some result and access a pointer to a UIView (a UILabel for example) and update it's content.
    Now, is this model correct? I'm running in cases where setting the UILabel.text from the thread sometimes work, sometimes doesnt. I'm not sure how to debug. If I change the thread call to a standard method call (which blocks until results are ready) the text is updated correctly.
    Any hints?

    http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadS afetySummary/chapter950_section2.html

  • 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);
    }

Maybe you are looking for

  • Disk Utility backup not working under Cmd R mode

    I upgraded my OS to 10.8.2. After doing so, when I do my normal system backup with Disk Utility, the system goes into sleep mode and the backup stops. I've done this many times in the past so I am not new to this.  I've read a few articles/posts with

  • External hard drive won't connect

    I have been using an external drive to transport material from an old computer to the Macbook Pro.  Normally I have used the firewire 400 port on both ends of the journey.  Suddenly, the MacBook will not connect to the hard drive.  I meticulously pow

  • Airport Express operating sytstem support

    Just got my airport express and it says that Mac OS X 10.5.2 won't support it? Help?

  • Time Capsule Connection failed

    Hello together. I was hoping that 10.5.3 will solve my problem but it wasn't the case. When I open finder and try to access the TC always for the first time I get the connection failed message. When I click on harddisk and than back to TC the connect

  • TinyXML,NanoXML,KXML etc..

    Hi there.. I need to use any one the above parser for parsing the xml document which is in String format..Can u help in how to actually put all the required parser classes into Midp applications..or either to set classpath for that parser.. Mail me A