"Safe" delete of Thread class from a Vector

I need to be able to delete a thread class object from a vector.
1) Is it safe to do so immedately after calling xyz.stop() ?
2) If so, does Java clean all the thread stuff up automatically ?
3) If not, is there something else I should do to clean up?

The stop method of class Thread is deprecated, however it's still possible to stop this thread. A thread's memory should become available for garbage collection the moment it is no longer executing, and it is no longer being reffered to.
To stop your thread, you need to set a boolean flag that is available to it to false:
Thread myThread = new Thread()
     public boolean stopRunning = false;
     public boolean threadComplete = false;
     public void run()
          while(!stopRunning)
               doSomething();
          threadComplete = true;
}If you are doing something involving blocking I/O inside your thread, you're going to need to interrupt the thread after setting this public flag to true in order to get it to stop executing.
Then you can simply remove it's refference from that Vector, and it will become elligable for Garbage collection the moment it becomes inactive.
-Jason Thomas.

Similar Messages

  • Vector manipulation for the Thread Class

    Hello everyone,
    Trying to create a producer consumer class
    Please help with consumer method.
    Here is my code:
    // Class
    import java.util.*;
    public class ProducerConsumer
         // A private Vector field.
          Vector vector = new Vector();     
               Object element;
         // A flag to indicate completion.
         private boolean produceFlag=false;
         // A method setDone() to indicate completion.
         public void setDone()
              produceFlag=true;
         // A method isDone()  to check completion.
          public boolean isDone()
               if (produceFlag)
                    return false;
               else
                    return true;
              // A produce() method  - The produce method checks if the vector is empty.
              // If it is, it will get a random number 'x' between 1 and 10.
              // The produce method then gets 'x' number of random numbers between 20 and 30,
              // displays the number on your screen and inserts them into the vector and notify
              // other threads that it is done. If the vector, is not empty then the produce method
              // just waits. You can use the following formula
              // to get random numbers between a range:
         public  synchronized void produce()
         try
              if (vector.isEmpty())                
                   int range =1;
                   range = (int) (Math.random() * 10);                
                   System.out.println("hello" + range);
                   for(int i=0;i<range;i++)
                        // convert int to Integer Object.
                        Integer I=new Integer((int) ( ( i - i + 1) * Math.random() + i ));                    
                        vector.addElement(I);                                                            
                   //loop thought the elements in a vector to print
                   for (int j=0; j < vector.size(); j++)
                        // set reference to each element inside the vector as Object.               
                        element=vector.elementAt(j);
                        /* cast the object variable to Integer.
                        ** call intValue() method of Integer
                        ** object that returns the int
                        ** inside an Integer Object.
                        // print the int just extracted.
                        System.out.println("Integer Found: " + ((Integer) element).intValue());
                        notifyAll();
                        setDone() ;
                   else
                        // Vector is not empty - it waits
                        wait();
                        System.out.println("i am not empty");                    
              }          // exception throws by wait().
              catch (InterruptedException e)
                   System.out.println(e.toString());
         // A consume method - The consume() method checks
         // if the vector is empty.
         // If it is, it checks if the producer is done.
         // If it is - the program exits.
         // If the producer is not done the consumer just waits. 
         // If the vector is not empty, the consume method
         // retrieves at most three items in FIFO
         // (First In First Out)
         // order from the vector, displays the numbers on your screen
         // and
         //  removes them from the vector.
         // If there are less then three items -
         // the consumer consumes all. If there are more than or
         // equal to three items, the
         // consumer consumes three items.
          public  synchronized void consume()
              try
                   if (vector.isEmpty())
                     if (isDone() )
                                    System.out.println("Done");
                                    System.exit(0);
                          else
                                    System.out.println("wait");
                                    wait();
                   else
                        // Consume retrives at most three items (1in,out)
                        // from vector, display the number on the screen
                        // removes from items from vector
                        // if less then 3 delete them all
                        for (int j=0; j < vector.size(); j++)
                             System.out.println("Integer Found: " + ((Integer) element).intValue());
                             vector.removeElementAt(j);      
              catch (InterruptedException e)
                   System.out.println(e.toString());
    // exception throws by wait().
    }THANKS A LOT FOR YOUR HELP:)

    How do I implement the logic to retrieves at most
    three items in (First In First Out) and removes them
    from the vector.
    If there are less then three items - the consumer
    consumes all. If there are more than or equal to
    three items, the consumer consumes three items.You start by looking at the javadocs for Vector to determine which methods on it might help you....
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

  • 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

  • Help! how to refresh the JTable of a class from another thread class

    there is an application, in server side ,there are two classes, one is a class called face class that 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

    thank you very much !
    i tried it ,but the TableModel i used like this ,and how to change the TableModel?
    here the files of mine ,pls give me some 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(){
    }

  • Accessing object of the main class from the thread

    Hi, I'm having problem accessing object of the main class from the thread. I have only one Thread and I'm calling log.append() from the Thread. Object log is defined and inicialized in the main class like this:
    public Text log;  // Text is SWT component
    log = new Text(...);Here is a Thread code:
    ...while((line = br.readLine())!=null) {
         try {
              log.append(line + "\r\n");
         } catch (SWTException swte) {
              ErrorMsg("SWT error: "+swte.getMessage());
    }Error is: org.eclipse.swt.SWTException: Invalid thread access
    When I replace log.append(...) with System.out.println(..) it works just fine, so my question is do the log.append(..) the right way.

    This is NOT a Java problem but a SWT specific issue.
    It is listed on the SWT FAQ page http://www.eclipse.org/swt/faq.php#uithread
    For more help with this you need to ask your question on a SWT specific forum, there is not a thing in these forums. This advice isn't just about SWT by the way but for all specific API exceptions/problems. You should take those questions to the forum or mailing list for that API. This forum is for general problems and exceptions arising from using the "core" Java libraries.

  • Deleting RFC classes from model

    Hi,
    I need to delete RFC classes from a model. The model is used in a different DC and I wouldn't like to remove all the references to the model as the risk to mess everything up seems high.
    However my RFC classes are never used, I would like to delete just them all, but the delete context menu item is disabled.
    Can anyone help?
    Thanks, points will be awarded
    Vincenzo

    Hi,
             One of the possibility I see is, double click on the model class and in properties pane check the path and physically remove the class from file system level. But try this on a sample project and see if there are no build errors. I don't think just leaving the model class like that will  make any difference in performance.
    Regards
    Ramesh.

  • Is thare a way to delete extre genres catagories from ipod classis when pluged in to computer I con not finde any way to do so?

    Is thare a way to delete extra genres categories from ipod classic?When plugged in to computer I can not find any kind of option?

    Of course. Simply change the genre of the songs so that none of your songs have the genre you wish to get rid of.
    You have two ways of showing the genre in iTunes. So if you cannot already see the genre, choose one of the following methods:
    Select View/As List and then select View/View Options and put a tick-in-the-box for Genre. Now that you can see the genre, simply select the songs with the genre you wish to change and type in the genre you do want.
    Select View/Column Browser and then select View/Column Browser/Genre (so that genre is ticked). This time, in the top browser column (genre) scroll down to and select the genre. Now all songs with that genre are shown in one group. Either a.) change them one at a time (if choosing different "new" genres) or b.) select all of them at once - and then select File/Get Info/Info/Genre,  and replace the genre.
    A genre is only shown if there is at least one song with that genre.

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • How do you delete an email address from your iPhone that's not in your contacts?

    How do you delete an email address from your iPhone that's not in your contacts?

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode

  • HT4847 I am unable to delete the last backup from icloud, i checked my all device setting but it still say "cannot delete icloud this time because it is in use,"Please tell me what should i do.

    I am unable to delete the last backup from icloud, i checked my all device setting but it still say "cannot delete icloud this time because it is in use,"Please tell me what should i do                             

    It still didn't work...
    Within this commonfiles\apple folder, there is only one folder, labeled "Internet Services." Within this folder, there are 6 folders, labeled:
    APLZOD.resources
    BookmarkDAV_client.resources
    CoreDAV.resources
    iCloud.resources
    iCloudServices.resources
    ShellStreams.resources
    Within all but CoreDAV and BookmarkDAV_client, there are multiple different folders, all labeled starting with a two letter (acronym I believe, for different languages) then .lproj (for example, a folder is labeled "ar.lproj".
    In each of the folders of APLZOD.resources, there is a file labeled "APLZODlocalized.dll."
    In all of the folders containing the multiple .lproj folders, there are likewise "name"localized.dll files contained.
    In the BookmarkDAV_client and Core DAV folders, they each contain only one file, "Info.plist"
    I attempted to delete all of these files, and still, the FileAssassin could not delete them. I unlocked one of them for instance, and I tried to delete the file myself (thru windows explorer and just clicking delete), and I still had the same issue of coming eventually to the window requesting me to "try again" to have permission.
    What can I do?? I'd like to avoid Unlocker, but if it really is a reliable and SAFE program, and someone knows a SAFE place to download it from, I'd appreciate it very much so!!
    thanks!!

  • Iphone 5 - I am trying to delete message threads and once I do, I go to text someone else and it won't send. HELP? I just don't want those messages on my phone anymore.

    Iphone 5 - I am trying to delete message threads and once I do, I go to text someone else and it won't send. HELP? I just don't want those messages on my phone anymore. I have tried to restart my phone but when I do, the "deleted" threads show back up on my phone. I use iOS 7.1.

    Hello Makayla,
    It sounds like you're deleted message threads keep coming back after you restart the devie. I recommend starting by quitting all the running apps on your phone:
    iOS: Force an app to close
    Double-click the Home button.
    Swipe left or right until you have located the app you wish to close.
    Swipe the app up to close it. 
    When you have done that restart the device and test the issue again:
    iOS: Turning off and on (restarting) and resetting
    If the issue persists, backup your device to iTunes and then restore it as a new device and verify that it works. 
    How to erase your iOS device and then set it up as a new device or restore it from backups
    If it does, then restore your backup to either verify it still works and the software just needed reinstalled, or isolate the issue to the backup file itself. 
    Thank you for using Apple Support Communities.
    Regards,
    Sterling

  • How to kill one class from another class

    I need to dipose one class from another class.
    So that first i have to find what are all threads running in that class and then to kill them
    Assist me.

    Subbu_Srinivasan wrote:
    I am explaining you in clear way
    No you haven't been.
    >
    In my application i am handling many JInternalFrame.Simultaneously i am running working on more than one frame.
    Due to some poor performance of some thread in one JInternalFrame,the thread is keeps on running .
    i could not able to proceed further on that screen.
    So i have to kill that JInternalFrame.Yoinks.
    To be begin with your problem sounds like you are doing everything in one thread. So stop doing that. Second when you get it split up and if a task is taking too much time then interrupt it. No kill. Interrupt. This means the worker thread needs to check sometimes if it has been interrupted.

  • Can I delete an email account without deleting the previous emails from it

    I have several emails from my own website ([email protected]) set to POP in Mail. Because of an overrun of spam, I disabled one of the accounts in Mail, and then deleted in at my website account. I have 2 others that I wasn't using, so I did the same. I didn't want to delete them in Mail, because I heard that would delete all the emails from it. So I just disabled them. But I see in Connection Doctor that they are still trying to connect to my website to retrieve email. Do I need to completely delete them from Mail? And if I do, if the emails are all moved out of the Inbox into folders I've created (mostly smart mailboxes) are they safe from being deleted? Will it only delete from Inbox, Send, and Trash?
    Thank you.

    Select the messages you want to keep, then select
    Message > Archive
    from the menu bar. A new mailbox will be created for each account from which you archive messages, and the messages will be kept when you delete the account and its mailboxes. Nevertheless, be sure to back up all data before making any changes.

  • How do i delete a Facebook event from my iPhone 5? (there is no delete button or edit button)

    Hi
    I cannot delete an facebook event from my Iphone 5. This event has been accepted by email invite.
    There is no edit or delete button at the top or bottom of the screen when I tap the event to search out its details.
    How do I remove such an event from my Ical calendar on my Iphone 5?

    I am not sure how this works but it seems that it may be all or nothing.
    To turn off Facebook events on your device:
    Settings > Facebook > Calendars > Off
    If you do not want to disable everything, maybe this thread will help:
    https://discussions.apple.com/thread/4349443

Maybe you are looking for

  • Upgrade path  11.5.9 to R12.1.3..??

    Hi All, Our Current Environment. OS : RHEL 4 update 8 (32 bit) EBS Version : 11.5.9 Database :9.2.0.8 We are planning to upgrade EBS from 11.5.9 to R12.1.3. Is below path is corerect. *Upgrade database from 9.2.0.8 to  11.1.0.7 *lay down R12.1.1 file

  • Safari Frame Rows Bug (white block)

    http://www.selfcrew.com/websitetest/album_dubberneck.html I'm building a site that uses framesets (outdated I've heard). None the less, on load, Safari will sporadically add a giant white space between the top and bottom frames. The big white space w

  • Why not use paper label on finished DVD project?

    I also use printed paper labels for my DVD covers why not use them? please advise?

  • Pantone color

    hi all, i would like to know does java graphics support color in pantone?i would like to export image with pantone color, thx!

  • Downloading and running files

    Hi there, I am wondering if I can develop a ac code to download file from my secure server and run the file into the local PC using Adobe AIR application with Flex. I have notice there is FileReference.download() method; however, this method displays