Can a parent thread kill a child thread?

I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
import java.net.*;
import java.io.*;
import java.util.Date;
public class ServerPing extends Thread {
  String [] args;
  public static void main(String[] args) throws Exception {
    ServerPing sp = new ServerPing(args);
    sp.start();
  ServerPing(String [] args) {
    this.args = args;
  public void run() {
    Pinger pinger = new Pinger(this);
    pinger.start();
    try {
      sleep(30000);
    catch (InterruptedException x) {
      System.exit(0); // this is ok. It means the pinger interrupted.
    System.out.println("TIMEOUT");
    System.exit(1);
class Pinger extends Thread {
  Thread p = null;
  Pinger (Thread p) {
    this.p = p;
  public void run() {
    try {
      URL simpleURL = new URL("http://localhost:7001/ping.jsp");
      BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
      System.out.println(inputLine);
      in.close();
      p.interrupt();   // <<-- interrupt the parent
    catch (Exception x) {
      x.printStackTrace();
}

Similar Messages

  • Killing Parent thread can kill child thread

    hi frnds
    can u help me on thread
    i want to know if i am kill my parent thread.can it automatically kill chhild thread also.
    and i want to know is there any way in java to kill thread
    plz reply

    ajju29 wrote:
    and i want to know is there any way in java to kill threadNo, not safely and not reliably. Since there's no way to "kill" a thread without its cooperation, the previous question is not relevant as well.
    What you want to do is set some flag that your thread periodically checks and maybe send an signal and/or interrupt to tell the thread to check the flag earlier. The thread should then quit on its own.
    Everything else is unfixably broken.

  • Child and Parent Threads

    I have a parent thread class PThread which
    instantiates some child threads CThread in its run()
    method..
    Now Child threads need to give their status/information
    back to Parent thread periodically.
    Can I child thread callback any function of Parent
    thread

    Actually in my case, 1 parent Thread is running and it instantiates multiple child Threads (the number will be decided based on input from some file)....Now these Child Threads are doing some measurements...Each Child Thread is maintaining a bool variable
    "isActive"...If the measurement is not bein taken, it sets the isActive flag to false, otherwise true...(Different Child threads have their own "isActive" Status)...
    Now, there are Some other classes in System who are interested in knowing which Measurements are Active....(that means they want to know the status of Individual Child threads).....These classes are
    interacting with Parent class only....
    That's why I wanted individual Childs to update their current status
    periodically to Parent , so that when Parent is asked this information
    from Other classes, it can Consolidate and present the data....
    This was the only purpose, why I asked whether we can call from
    inside Child Thread, any functon of Parent Thread..
    What I understood from your comments that if Child Thread has access to Parent Thread's Object....(wich should be passed to it during new),
    it can callback Parent's functions.
    That should solve the purpose.....
    Regarding stopping of threads, Parent thread is itself gets information/interrupt from some other class to stop itself... when it
    gets the information, it will stops the Child threads too...I was thinking of calling some stop()
    function of individual child threads which will call their interrupt()..
    And at the end I will call the interrupt() of Parent class....
    I don't know much about usage of join(), so will have to study more
    about how can I do it better.
    Also one thing more:-
    Both Child and Parent Thread classes are extending Thread.
    They don't have to extend from any other class...I have to
    write specific functionality in run() function of parent and class.
    Should I change it to runnable....Why did you advised against
    extending threads

  • Vi server parent kill his child

    "I use a VI-server (parent vi) to start another VI (child) with a closed front panel. When the parent stops running he killed his child. How can I avoid this? There is no problem when the front panel of the child stays open."
    -posted

    You should open a reference to the child from itself, as long as vi's without front panel need them to stay open. If not, LV considers you closed the front panel because you wanted to exit. Be sure the child vi has enough time to open the reference before closing the parent vi, else it won't work.
    Hope this helps

  • Can't start Thread from modal JDialog.

    Hi,
    this is a part of my code. I can't start the scanThread from the object WaitingDl. But if i close the modal JDialog (WaitingDl) the scanThread starts, please help:
    Thread scanThread = new Thread() {
    public void run() {                       
    // do something ....
    WaitingDl waitFrame = new WaitingDl("Waiting process", parent, scanThread, "Please wait ...");
    class WaitingDl extends JDialog {
    public WaitingDl(String title, JFrame parent, Thread thread, String waitingText) {  
    // a modal Dialog
    super(parent,true);
    // This command doesn't work!
    scanThread.start();
    Thanks!

    Hi,
    As suggestion :
    I think your JDialog is modal and visible by default, so
    when you invoke the contructor :
    WaitingDL d=new ......
    you enter to "modal state" so the Event thread is blocked and this append when you invoke super at
    contructor level.
    If you set your dialog not visible you can do :
    WaitingDL d=new .........
    // at this moment the contructor is invoked but the event thread is not blocked so your thread is started
    d.setVisible(true);
    // at this point the dialog is visible you enter at a modal state but your thread is running
    Hope this help
    Bye

  • Catching Exception in Parent Thread

    Hi Pros,
    I have a thread having try-catch block. Whatever exception I am catching into catch block should be thrown to be handled by Parent thread.
    Is there any way to do this.
    Thanks,
    Abhijit

    You can't literally throw to the parent thread per se, and the concept of doing so doesn't really make any sense. But using UncaughtExceptionHandler, you can give some control to the parent thread.
    package scratch;
    public class Uncaught {
      public static void main (String[] args) throws Exception {
        Thread t = new Thread(new MyRunnable());
        Thread.UncaughtExceptionHandler eh = new MyUEH ();
        t.setUncaughtExceptionHandler (eh);
        t.start();
      static class MyRunnable implements Runnable {
        @Override
        public void run () {
          System.out.println ("Thread name is: " + Thread.currentThread ().getName ());
          throw new RuntimeException("Can't catch me, I'm the gingerbread thread!");
      static class MyUEH implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException (final Thread t, final Throwable e) {
          System.err.println ("The uncaught exception stack trace for Thread " + t.getName() + " is: ");
          e.printStackTrace ();
    }

  • Name of the Parent Thread.

    How can I know the name of the parent thread( not the threadgroup). If I create any theads in the main() function...these threqads have to be spawned by the main.Thread. How can I get the name of the Parent thread which has spawned my thread?
    Thank you.

    the 0th element of the ".getParent()" call on the current threads threadGroup?
    Doesn't seem to be a formal way, but you could create a system by extending the Thread class.

  • How can a parent restrict a child's access to a PARENT'S PRE-EXSISTING iTunes account via iCloud's Family Sharing Program?

    How can a parent restrict a child's access to a PARENT'S PRE-EXSISTING iTunes account via iCloud's Family Sharing Program?  To explain further... I have a young son who is on my iCloud family sharing program... I am excited to be able to share SOME of my music in my iTunes library, but there are some songs and music videos that are not age appropriate for him and currently there is no way to restrict him from viewing and downloading anything off of my iTunes library.  Yes, I suppose I can delete the songs he shouldn't have access to, but I don't think I should have to do that... I paid for them and still like them and listen to them while I work out or am without my kids.  Is there a way for me to personally select which songs/videos I would like to "hide" from my children in an effort to shield them from inappropriate content?

    Hello ggg39,
    Welcome to the Apple Support Communities!
    I understand that you have some content in your iTunes library that you would like to restrict access for the child set up on Family Sharing with you. To do this, you can set restrictions on the child’s device as described in the attached article. 
    Family Sharing - Apple Support
    Now kids under 13 can have their own Apple IDs. As a parent or legal guardian, the family organizer can create an Apple ID for a child and add the child to the family group automatically. Ask to Buy is turned on by default, and the organizer can also limit the content kids have access to on their devices through Restrictions on an iOS device or parental controls in OS X and iTunes.
    For more information on restrictions and how to set them up, please reference the next attached article. 
    About Restrictions (parental controls) on iPhone, iPad, and iPod touch - Apple Support
    Have a great day,
    Joe

  • How can provide parent-child nodes relation ships?

    how can provide parent-child nodes relation ships?

    I was under the impression that scenegraph is like a JTree. But in JavaFX only leaf node rendering in scenegraph. This situation was confusing my mind. In JavaFX CustomNode must be extending and return a group for custom leaf. If we want to a create parent-child node hierarchy we are create CustomNode that return a group and this group contain an another group,etc. So there is maybe only a way. If you learning to JavaFX first time.This way don't look familiar.

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

  • Can a dead thread be alive again !!

    can a dead thread be alive again ?
    i have added some threads in a thread group. and then called its activeCount() methods.
    it is giving results like this....
    the active count:10
    the active count:5
    the active count:2
    the active count: 1
    the active count: 2 // dead thread alive ?
    the active count: 0
    is it feasible theoretically ? i am getting that kind of output

    as most of the time, the API doc saves the day :
    activeCount
    public int activeCount()
    Returns an estimate of the number of active
    tive threads in this thread group. The result might
    not reflect concurrent activity,
    number of activetive threadswhat is the meaning of active here ? alive() ? there is a isalive() method already ......
    and might be
    affected by the presence of certain system threads......u mean system thread can leak into my threadgroup....well
    Due to the inherently imprecise nature of the
    the result, it is recommended that this method only
    be used for informational purposes.
    Returns:
    an estimate of the number of active threads
    threads in this thread group and in any other thread
    group that has this thread group as an ancestor.
    Since:
    JDK1.0

  • HT1766 I have iPhone 4. I deleted a thread of SMS by mistake. Last back on iCloud was on 14/05/2013. How I can retrieve this thread of SMS till 19/05/2013!?

    I have iPhone 4. I deleted a thread of SMS by mistake. Last back on iCloud was on 14/05/2013. How I can retrieve this thread of SMS till 19/05/2013!?

    You're welcome.
    Text messages are included with the iPhone's backup.
    http://support.apple.com/kb/HT4946
    iTunes will back up the following information
    Contacts* and Contact Favorites (regularly sync contacts to a computer or cloud service such as iCloud to back them up).
    App Store Application data including in-app purchases (except the Application itself, its tmp and Caches folder).
    Application settings, preferences, and data, including documents.
    Autofill for webpages.
    CalDAV and subscribed calendar accounts.
    Calendar accounts.
    Calendar events.
    Call history.
    Camera Roll (Photos, screenshots, images saved, and videos taken. Videos greater than 2 GB are backed up with iOS 4.0 and later.)
    Note: For devices without a camera, Camera Roll is called Saved Photos.
    Game Center account.
    Home screen arrangement.
    In-app purchases.
    Keychain (this includes email account passwords, Wi-Fi passwords, and passwords you enter into websites and some other applications. If you encrypt the backup with iOS 4 and later, you can transfer the keychain information to the new device. With an unencrypted backup, you can restore the keychain only to the same iOS device. If you are restoring to a new device with an unencrypted backup, you will need to enter these passwords again.)
    List of External Sync Sources (MobileMe, Exchange ActiveSync).
    Location service preferences for apps and websites you have allowed to use your location.
    Mail accounts (mail messages are not backed up).
    Installed Profiles. When restoring a backup to a different device, installed configuration profiles are not restored (such as accounts, restrictions, or anything which can be specified through an installed profile.) Any accounts or settings that are not associated with an installed profile will still be restored.
    Map bookmarks, recent searches, and the current location displayed in Maps.
    Microsoft Exchange account configurations.
    Network settings (saved Wi-Fi hotspots, VPN settings, network preferences).
    Nike + iPod saved workouts and settings.
    Notes.
    Offline web application cache/database.
    Paired Bluetooth devices (which can only be used if restored to the same phone that did the backup).
    Safari bookmarks, cookies, history, offline data, and currently open pages.
    Saved suggestion corrections (these are saved automatically as you reject suggested corrections).
    Messages (iMessage and carrier SMS or MMS pictures and videos).
    Trusted hosts that have certificates that cannot be verified.
    Voice memos.
    Voicemail token. (This is not the voicemail password, but is used for validation when connecting. This is only restored to a phone with the same phone number on the SIM card).
    Wallpapers.
    Web clips.
    YouTube bookmarks and history.
    * Your contacts are part of the backup to preserve recent calls and favorites lists. Back up your contacts to a supported personal information manager (PIM), iCloud, or another cloud-based service to avoid any potential contact data loss.
    http://support.apple.com/kb/HT4859
    What is backed up
    You get unlimited free storage for:
    Purchased music, movies, TV shows, apps, and books
    Notes: Backup of purchased music is not available in all countries. Backups of purchased movies and TV shows are U.S. only. Previous purchases may not be restored if they are no longer in the iTunes Store, App Store, or iBookstore.Some previously purchased movies may not be available in iTunes in the Cloud. These movies will indicate that they are not available in iTunes in the Cloud on their product details page in the iTunes Store. Previous purchases may be unavailable if they have been refunded or are no longer available in the iTunes Store, App Store, or iBookstore.
    You get 5 GB of free iCloud storage for:
    Photos and videos in the Camera Roll
    Device settings (for example: Phone Favorites, Wallpaper, and Mail, Contacts, Calendar accounts)
    App data
    Home screen and app organization
    Messages (iMessage, SMS, and MMS)
    Ringtones
    Visual Voicemails
    You can select which applications back up their data and see how much storage space each application is using:
    On your Home Screen, tap Settings
    Tap iCloud
    Tap Storage & Backup
    Tap Manage Storage
    Select the device you want to manage

  • Vi server killed his child when the server is ready

    I use a VI-server (parent vi) to start another VI (child). This child VI stay running while the parent stop. At this moment the parent kill his child too. How can I avoid this?

    Which LV version do you use ? I remeber there was a bug that prevented the
    child to stay running in 6.0; upgrade to 6.0.2 if needed.
    Jean-Pierre Drolet
    "RCMCVU" a écrit dans le message news:
    [email protected]..
    > But how can I avoid that the child would be killed when the front
    > panel of the child is closed. I think that this situation is
    > different, because it doesn't work.
    LabVIEW, C'est LabVIEW

  • SQL Server 2012 Management Studio:In the Database, how to print out or export the old 3 dbo Tables that were created manually and they have a relationship for 1 Parent table and 2 Child tables?How to handle this relationship in creating a new XML Schema?

    Hi all,
    Long time ago, I manually created a Database (APGriMMRP) and 3 Tables (dbo.Table_1_XYcoordinates, dbo.Table_2_Soil, and dbo.Table_3_Water) in my SQL Server 2012 Management Studio (SSMS2012). The dbo.Table_1_XYcoordinates has the following columns: file_id,
    Pt_ID, X, Y, Z, sample_id, Boring. The dbo.Table_2_Soil has the following columns: Boring, sample_date, sample_id, Unit, Arsenic, Chromium, Lead. The dbo.Table_3_Water has the following columns: Boring, sample_date, sample_id, Unit, Benzene, Ethylbenzene,
    Pyrene. The dbo.Table_1_XYcoordinates is a Parent Table. The dbo.Table_2_Soil and the dbo.Table_3_Water are 2 Child Tables. The sample_id is key link for the relationship between the Parent Table and the Child Tables.
    Problem #1) How can I print out or export these 3 dbo Tables?
    Problem #2) If I right-click on the dbo Table, I see "Start PowerShell" and click on it. I get the following error messages: Warning: Failed to load the 'SQLAS' extension: An exception occurred in SMO while trying to manage a service. 
    --> Failed to retrieve data for this request. --> Invalid class.  Warning: Could not obtain SQL Server Service information. An attemp to connect to WMI on 'NAB-WK-02657306' failed with the following error: An exception occurred in SMO while trying
    to manage a service. --> Failed to retrieve data for this request. --> Invalid class.  .... PS SQLSERVER:\SQL\NAB-WK-02657306\SQLEXPRESS\Databases\APGriMMRP\Table_1_XYcoordinates>   What causes this set of error messages? How can
    I get this problem fixed in my PC that is an end user of the Windows 7 LAN System? Note: I don't have the regular version of Microsoft Visual Studio 2012 in my PC. I just have the Microsoft 2012 Shell (Integrated) program in my PC.
    Problem #3: I plan to create an XML Schema Collection in the "APGriMMRP" database for the Parent Table and the Child Tables. How can I handle the relationship between the Parent Table and the Child Table in the XML Schema Collection?
    Problem #4: I plan to extract some results/data from the Parent Table and the Child Table by using XQuery. What kind of JOIN (Left or Right JOIN) should I use in the XQuerying?
    Please kindly help, answer my questions, and advise me how to resolve these 4 problems.
    Thanks in advance,
    Scott Chang    

    In the future, I would recommend you to post your questions one by one, and to the appropriate forum. Of your questions it is really only #3 that fits into this forum. (And that is the one I will not answer, because I have worked very little with XSD.)
    1) Not sure what you mean with "print" or "export", but when you right-click a database, you can select Tasks from the context menu and in this submenu you find "Export data".
    2) I don't know why you get that error, but any particular reason you want to run PowerShell?
    4) If you have tables, you query them with SQL, not XQuery. XQuery is when you query XML documents, but left and right joins are SQL things. There are no joins in XQuery.
    As for left/right join, notice that these two are equivalent:
    SELECT ...
    FROM   a LEFT JOIN b ON a.col = b.col
    SELECT ...
    FROM   b RIGHT JOIN a ON a.col = b.col
    But please never use RIGHT JOIN - it gives me a headache!
    There is nothing that says that you should use any of the other. In fact, if you are returning rows from parent and child, I would expect an inner join, unless you want to cater for parents without children.
    Here is an example where you can study the different join types and how they behave:
    CREATE TABLE apple (a int         NOT NULL PRIMARY KEY,
                        b varchar(23) NOT NULL)
    INSERT apple(a, b)
       VALUES(1, 'Granny Smith'),
             (2, 'Gloster'),
             (4, 'Ingrid-Marie'),
             (5, 'Milenga')
    CREATE TABLE orange(c int        NOT NULL PRIMARY KEY,
                        d varchar(23) NOT NULL)
    INSERT orange(c, d)
       VALUES(1, 'Agent'),
             (3, 'Netherlands'),
             (4, 'Revolution')
    SELECT a, b, c, d
    FROM   apple
    CROSS  JOIN orange
    SELECT a, b, c, d
    FROM   apple
    INNER  JOIN orange ON apple.a = orange.c
    SELECT a, b, c, d
    FROM   apple
    LEFT   OUTER JOIN orange ON apple.a = orange.c
    SELECT a, b, c, d
    FROM   apple
    RIGHT  OUTER JOIN orange ON apple.a = orange.c
    SELECT a, b, c, d
    FROM   apple
    FULL OUTER JOIN orange ON apple.a = orange.c
    go
    DROP TABLE apple, orange
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to get the parent window in sub-child controller class in javafx?

    how to get the parent window in sub-child controller class in javafx?

    You can get the window in which a node is contained with
    Window window = node.getScene().getWindow();Depending when this is invoked, you might want to check the Scene is not null before calling getWindow().
    If the window is a stage that is owned by another window, you can get the "parent" or "owner" window with
    Window owner = null ;
    if (window instanceof Stage) {
      Stage stage = (Stage) window ;
      owner = stage.getOwner();
    }

Maybe you are looking for

  • How can I add a header/footer to a document?

    I am using Adobe X Standard, version 10.1.2 and everything I am reading tells me to go to tools>pages>Header & Footer>Add Header & Footer, but once I click on tools to the left, the only options I have are export and create pdf files and send files.

  • Login Applet Help

    Hello I am trying to write a applet that allows me to login to a particular page on my site. I am new to java and have looked some books on the subject. I thought I would be able to manage it myself but I cant for the life of me do it. Here is the co

  • Why can't people view my email attachments?

    Hi, I regularly send out emails using Mail with JPEG attachments but many people cannot see them. They simply get the following type of code/jargon. What is going on and what is the solution? = --Apple-Mail-6--884313368 Content-Transfer-Encoding: bas

  • Run Extended Analtytics / Create Star Schema based on Process Management Level Status

    Dear HFM Gurus, I have come across a requirement where I would need to automate extended analytics extraction based on Review Level / Approve Status of Entities. Once the Process Management Status changed to Approve status from Review Level 3 or they

  • New using databases in Java

    First of all hello, this is my first post in the Java oracle forum, I know basic knowledge of java(school) and some mysql database(self thought) too. I wanted to make a java app where i could use a database inside the same jar, but i am not pretty su