Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

Hi,
I am using JMenu and switchable JPanels.
When I click on a MenuItem the follownig code should starts
    cards.add(listenPanel,  "listenPanel");
    cardLayout.show(cards, "listenPanel");
    try{
      Thread.sleep(5000); //in ms
      PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
    } catch(Exception e) {
      e.printStackTrace();
    }It seems to be what I want to reach, but it does not work the way I want it to.
I would like the Panel to show right away, then wait 5s and then play the sound.
BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
Can you tell me why this is??

This might be what you want
package tjacobs.thread;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.Semaphore;
import tjacobs.ui.Eyes;
import tjacobs.ui.util.WindowUtilities;
public class ThreadForMultipleAnytimeRuns extends Thread {
     private Runnable mRunnable;
     private Semaphore mSemaphore;
     public ThreadForMultipleAnytimeRuns(Runnable arg0) {
          super();
          init(arg0);
     private void init(Runnable r) {
          mRunnable = r;
          mSemaphore = new Semaphore(0);
          setDaemon(true);
     public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
          super(arg1);
          init(arg0);
     public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
          super(arg0, arg2);
          init(arg1);
     public void run () {
          try {
               while (!isInterrupted()) {
                    mSemaphore.acquire();
                    mRunnable.run();
          catch (InterruptedException ex) {}
     public void runAgain() {
          mSemaphore.release();
     public void runAgain(int numTimes) {
          mSemaphore.release(numTimes);
     public void stopThread() {
          interrupt();
     public int getSemaphoreCount() {
          return mSemaphore.availablePermits();
     public Runnable getRunnable() {
          return mRunnable;
     //The setRunnable method is simply not safe, and
     //trying to make it safe is going to effect performance
     //Plus I can't really see a gain in being able to set
     //The runnable on one of these threads. Just create
     //a new one!
     public synchronized void setRunnable(Runnable r) {
          if (getSemaphoreCount() > 0) {
               try {
                    wait();
               catch (InterruptedException ex) {
                    return;
          mRunnable = r;
     public static void main(String[] args) {
          final Eyes eyes = new Eyes(true);
          //eyes.addMouseMotionListener(eyes);
          Runnable r = new Runnable() {
               public void run() {
                    eyes.blink();
                    try {
                         Thread.sleep(100);
                    catch(InterruptedException ex) {}
          final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
          ar.start();
          eyes.addMouseListener(new MouseAdapter() {
               public void mouseClicked(MouseEvent me) {
                    ar.runAgain();
          eyes.setPreferredSize(new Dimension(60,20));
          WindowUtilities.visualize(eyes);
//          JFrame jf = new JFrame();
//          jf.add(eyes);
//          jf.pack();
//          jf.setLocation(100,100);
//          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//          jf.setVisible(true);
}

Similar Messages

  • Localizion resource problem about *.resx and Thread.CurrentThread.CurrentCulture

    Hello all,
      I have a strange question. I am building an application which is for US and other localizations
      In one project. I create different resources -- it is *.resx file.  For example
      They are Text.resx and Text.zh-Hans.resx files.
      At the start of the application I add the following code
       Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-Hans"); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("zh-Hans");
     in the later code, program access the Properties defined in *.resx files for different languages.
    Now here is question. The application works in one Win7 box. But it doesn't work in another Win7 box.
    In the Win7 box which has problem, the application always displays the English text (which are defined at Text.resx )
    It doesn't display the simplified Hans defined in Text.zh-Hans.resx.
    I have tried several system settings, but nothing works in that Win7 box.
    Does any one has any idea with it?
    Thanks
    Good luck

    @startor
    I am glad to know you solved this problem and thanks for sharing the solution.
    It will be very beneficial for other community members who have the similar questions.
    Best Regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Using Thread.currentthread.sleep but not delaying appropriately

    Ok, here it goes. Im currently using the thread.sleep method to delay the changing of the text within some labels. I have 3 labels which represent some arrays. I then sort the arrays. Im trying to throw a delay in so that the user can see the changes happen to the array. Although, when I call the wait.millisec(1000) in (the sleep function I threw into its own wait class) it seems that the waiting all happens at the end. I dont see it during the loop to show the arrangement changes within the arrays. I stepped through the code using the debugger, but it doesnt seem to help.
    Look in the buttonListener within the FourX class.
    * SortTest.java                                   Author:Tim Dudek
       This trivial program tests the insertion sort and selection sort
       subroutines.  The data is then shown graphically.
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SortTest {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class FourX extends JPanel {
         static final long serialVersionUID = 1L; //eclipse echo problem
         private JLabel lblO, lblI, lblS;
         private JButton sort;
         public FourX(){//JLabel lblOrig,JLabel lblSS, JLabel lblIS){
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              SortTest.lblSS = new JLabel ("");
              SortTest.lblOrig = new JLabel ("");
              SortTest.lblIS = new JLabel ("");
              lblO = new JLabel("Orginal", JTextField.LEFT);
              lblI = new JLabel("Insertion Sort", JTextField.LEFT);
              lblS = new JLabel("Selection Sort", JTextField.LEFT);
              sort = new JButton("Sort");     
              sort.addActionListener(new buttonListener());
              SortTest.lblSS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblSS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblSS.setBorder(BorderFactory.createLineBorder (Color.RED, 3));
              SortTest.lblIS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblIS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblIS.setBorder(BorderFactory.createLineBorder (Color.BLUE, 3));
              SortTest.lblOrig.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblOrig.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblOrig.setBorder(BorderFactory.createLineBorder (Color.BLACK, 3));
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblO);
              add(SortTest.lblOrig);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblS);
              add(SortTest.lblSS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblI);
              add(SortTest.lblIS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(sort);
         private class buttonListener implements ActionListener{
              public void actionPerformed (ActionEvent event){
              // sort A into increasing order, using selection sort
                   for (int lastPlace = SortTest.A.length-1; lastPlace > 0; lastPlace--) {
                        Wait.milliSec(50);
                   //Find the largest item among A[0], A[1], ... A[lastPlace],
              // and move it into position lastPlace by swapping it with
              // the number that is currently in position lastPlace
                        int maxLoc = 0; // location of largest item seen so far
                   for (int j = 1; j <= lastPlace; j++) {
                        if (SortTest.A[j] > SortTest.A[maxLoc])
                   maxLoc = j; // Now, location j contains the largest item seen
                   int temp = SortTest.A[maxLoc]; // swap largest item with A[lastPlace]
                   SortTest.A[maxLoc] = SortTest.A[lastPlace];
                   SortTest.A[lastPlace] = temp;
                   Wait.milliSec(100);//<------------ waiting???>
                   SortTest.lblSS.setText("");
                   for (int i = 0; i < SortTest.A.length; i++){
                        SortTest.lblSS.setText(SortTest.lblSS.getText() + " "     + SortTest.A[i]);
                   Wait.oneSec();//<------------ waiting???>
                   // sort the array A into increasing order
                   int itemsSorted; // number of items that have been sorted so far
                   for (itemsSorted = 1; itemsSorted < SortTest.B.length; itemsSorted++) {
                        // assume that items A[0], A[1], ... A[itemsSorted-1] have
                        // already been sorted, and insert A[itemsSorted] into the list.
                        int temp = SortTest.B[itemsSorted]; // the item to be inserted
                        int loc = itemsSorted - 1;
                        while (loc >= 0 && SortTest.B[loc] > temp) {
                             SortTest.B[loc + 1] = SortTest.B[loc];
                             loc = loc - 1;
                        SortTest.B[loc + 1] = temp;
                        Wait.milliSec(100);//<------------ waiting???>                    SortTest.lblIS.setText("");
                        for (int i = 0; i < SortTest.B.length; i++){
                             SortTest.lblIS.setText(SortTest.lblIS.getText() + " "     + SortTest.B[i]);
    public class Wait {
         public static void oneSec() {
              try {
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public static void milliSec(long s) {
              try {
                   Thread.currentThread().sleep(s);
              catch (InterruptedException e) {
                   e.printStackTrace();

    Wow, ok. this is extrodinarily confusing. I read the tutorials, but they're not easy to follow.
    So, what I did was at the entry point:
    public class SortTest implements Runnable {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            (new Thread(new SortTest())).start();
       public void run(){
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    Ok, as I understand, this creates the initial thread to build the gui. Now you suggest that when the user hits "sort" that a second thread be created to handle the sorting routine.  From what I understand I can only inherit from one class in java.  My buttonListener already implements ActionListener. I obviously cant implement ActionListener and Runnable.  Do you have a suggestion? Maybe a link to an example?
    I'm pretty lost. 
    Tim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Difference between LockSupport.parkUntil and Thread.sleep method

    Hi
    Could someone please explain the difference between LockSupport.parkUntil and Thread.sleep methods.
    Thanks in advance.

    javaLearner wrote:
    The thing that I am trying to understand is - the difference / correlation between the two methods mentioned.
    In the javadoc, there is a mention of correlation between the LockSupport methods park, unpark and the Thread methods suspend, resume - but not park and sleep.Then that suggests that there isn't any difference /correlation -- whatever you meant by that. Perhaps your question is like asking for the difference between a fish and a bicycle.
    Also, I would like to understand the statement
    These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. (from the javadoc)Again, you're going to have to explain what you don't understand about it.

  • Public static Thread currentThread() and multi core processors??

    Hello,
    I have the following basic question: what does public static Thread currentThread() mean in the context of multi core processors where several threads may execute concurrently?
    Any clue welcome,
    J.

    Hi balteo,
    When you invoke Thread.currentThread(), you get the reference of the current thread : the thread where you make the call.
    Just try :
    System.out.println("My program is running thread : " + Thread.currentThread().getName());
    mean in the context of multi core processors where several threads may execute concurrently?Several threads may run concurrently with single core processors. The number of concurrent threads you may execute depends of the processors architecture and the OS.

  • I have a problem in this that i want to paas a form in a case that when user pres n then it must go to a form but error arises and not working good and threading is not responding

    made in cosmos help please need it
    using System;
    using Cosmos.Compiler.Builder;
    using System.Threading;
    using System.Windows.Forms;
    namespace IUOS
        class Program
            #region Cosmos Builder logic
            // Most users wont touch this. This will call the Cosmos Build tool
            [STAThread]
            static void Main(string[] args)
                BuildUI.Run();
            #endregion
            // Main entry point of the kernel
            public static void Init()
                var xBoot = new Cosmos.Sys.Boot();
                xBoot.Execute();
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                a:
                Console.WriteLine("------------------------------");
                Console.WriteLine("WELCOME TO THE NEWLY OS MADE BY THE STUDENTS OF IQRA UNIVERSITY!");
                Console.WriteLine("------------------------------");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("\t _____                                
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |");
                Console.WriteLine("\t|     |        |            |        
    |            |      |___________");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|     |        |            |        
    |            |                  |");
                Console.WriteLine("\t|_____|        |____________|         |____________|      ____________");
                string input;
                Console.WriteLine();
                Console.Write("\nAbout OS     : a");
                Console.Write("\nTo Shutdown  : s");
                Console.Write("\nTo Reboot    : r");
                Console.Write("\nStart Windows Normaly : n");
                Console.WriteLine();
                input = Console.ReadLine();
                if (input == "s" || input == "S"){
                    Cosmos.Sys.Deboot.ShutDown();
                else
                if (input == "r" || input == "R"){
                    Cosmos.Sys.Deboot.Reboot();
                else
                if (input == "a" || input == "A"){
                    Console.ForegroundColor = ConsoleColor.DarkBlue;
                    Console.Clear();
                    Console.WriteLine("\n\n\n-------------------------------------");
                    Console.WriteLine("version: DISPLAYS OS VERSION");
                    Console.WriteLine("about: DISPLAYS INFO ABOUT ANGRY OS");
                    Console.WriteLine("hello or hi: DISPLAYS A HELLO WORLD");
                    Console.WriteLine("MESSAGE THAT WAS USED TO TEST THIS OS!!");
                    Console.WriteLine("-----------------------------------");
                    Console.Write("You Want to know : ");
                    input = Console.ReadLine();
                    if (input == "version"){
                        Console.WriteLine("--------------------");
                        Console.WriteLine("OS VERSION 0.1");
                        Console.WriteLine("--------------------");
                    else
                    if (input == "about"){
                        Console.WriteLine("--------------------------------------------");
                        Console.WriteLine("OS IS DEVELOPED BY Qazi Jalil-ur-Rahman & Syed Akber Abbas Jafri");
                        Console.WriteLine("--------------------------------------------");
                    Console.Write("Want to go back to the main window");
                    Console.Write("\nYes : ");
                    string ans = Console.ReadLine();
                    if (ans == "y" || ans == "Y")
                        goto a;
                        Thread.Sleep(10000);
                    else
                    if (input == "n" || input == "N")
                        Thread.Sleep(5000);
                        Console.Clear();
                        for (int i = 0; i <= 0; i++){
                            Console.Write("\n\n\n\n\t\t\t\t\t  ____        ____   ___  
                            Console.Write("\n\t\t|\t\t |  |      |    |     
    |   |  | |  |  |");
                            Console.Write("\n\t\t|\t|    |  |----  |    |     
    |   |  | |  |  |---");
                            Console.Write("\n\t\t|____|____|  |____  |___ |____  |___|  |    |  |___");
                            Thread.Sleep(500);
                        Thread.Sleep(5000);
                        Console.Clear();
                        BootUserInterface();
                        Console.ReadLine();
    //                    Form1 fo = new Form1();
                    else{
                        for (int i = 0; i <= 5; i++){
                            Console.Beep();
                            Thread.Sleep(1000);
                            goto a;
                while (true);
            private static void BootUserInterface() {
                Thread t = new Thread(UserInterfaceThread);
                t.IsBackground = true;
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            private static void UserInterfaceThread(object arg) {
                Form1 frm = new Form1();  // use your own
                Application.Run(frm);
     

    Hi
    Jalil Cracker,
    >>when user pres n then it must go to a form but error arises and not working good and threading is not respondin
    Could you post the error information? And which line caused this error?
    If you want to show Form1, you can use form.show() method
    Form1 frm = new Form1();
    frm.Show();
    In addition, Cosmos is an acronym for C# Open Source Managed Operating System. This is not Microsoft product.If the issue is related to Cosmos, it would be out of our support. Thanks for your understanding. And you need raise an issue at Cosmos site.
    Best regards,
    kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • UrlConnection and Thread

    Hi all,
    Thread Tx uses UrlConnection to connect a HomeApp on Tomcat to do something
    HomeApp receives request, and sleeps for 100000milisec
    Thread Tx2 sleeps for 100milisec and wake up to interrupt Thread Tx
    I expected all operations inside Thread Tx will be destroyed..but the urlCon.getInputStream(); still waits for the server to response after Thread.interrupt();
    Does UrlConnection has its own thread ?
    how do i stop urlConnection from waiting for server's response after Tx.interrupt()?
    Runnable Rx1 = new Runnable(){
    public void run() {
        URLConnection urlCon = page.openConnection();
        urlCon.setDoInput(true);
        urlCon.setDoOutput(true);
        urlCon.setRequestProperty("Method", "POST");
        urlCon.connect();
        OutputStream rawOutStream = urlCon.getOutputStream();
        PrintWriter pw = new PrintWriter(rawOutStream);
        pw.write(this.property);
        pw.flush();
        pw.close();
        *urlCon.getInputStream();*  *// Tx thread got interrupted by Tx2,
                     //but this line of code still get executed.  It receives responses from Tomcat server*
    final Thread Tx = new Thread(Rx1);
    Tx.setName("LoginServlet-Thread");
    Tx.start();
    Runnable Rx2 = new Runnable(){
         public void run() {
              try {
                   Thread.currentThread().sleep(100);
                   if(Tx.isAlive()){
                        *if(Tx.isInterrupted())*
                        logger.info(Tx.getName() + " is already interrupted");
                                  else{logger.info("not interrupted yet");     
              } catch (InterruptedException e) {}
         Thread Tx2 = new Thread(Rx2);
         Tx2.start();thank you all
    Edited by: happy2005 on Jan 20, 2009 6:19 PM
    Edited by: happy2005 on Jan 20, 2009 6:22 PM
    Edited by: happy2005 on Jan 20, 2009 6:23 PM
    Edited by: happy2005 on Jan 20, 2009 6:24 PM

    how do you do that?
    UrlConnection doesn't have close method
    I did urlCon.getInputStream().close();but the close didn't take place until getting the stream completed.
    i want to stop / disrupt getInputStream from running.
    regards,

  • About LineStripArray and Thread

    Dear all,
    I want to create a lot of point and then use LineStripArray to connect them together. The user click the "Connect" button to create that the line can be added one by one with time delay 0.5 second. similiar animation. But it's does not work!?
    Thank you for your reply and solving!! There is my code fragment:
    int[] length = new int[1];
    length[0] = 4;
    LineStripArray lsa = new LineStripArray (4, LineArray.COORDINATES, length);
    try{
    //Try create a set of points to connect all of sphere
    Point3f[] connectPoint = {
    new Point3f(0.063f, 0.85f, 0.099f),//1
    new Point3f(0.083f, 0.81f, 0.02f),//2
    new Point3f(0.083f, 0.84f, 0.04f),//3
    new Point3f(0.085f, 0.91f, 0.03f)};
    for (int i = 0; i<connectPoint.length; i++)
    lsa.setCoordinate(i, connectPoint);
    Thread.currentThread().sleep(500);
    System.out.println("Count line No. " + i );
    }//Try block
    catch(InterruptedException ie){
    }//Catch block
    Appearance lineApp = new Appearance();
    lineApp.setColoringAttributes(green);
    Shape3D linelsa = new Shape3D(lsa, lineApp);
    linelsa.setUserData("lsa");
    tg.addChild(linelsa);Edited by: kklam on Apr 2, 2008 6:28 AM

    Dear all,
    I want to create a lot of point and then use LineStripArray to connect them together. The user click the "Connect" button to create that the line can be added one by one with time delay 0.5 second. similiar animation. But it's does not work!?
    Thank you for your reply and solving!! There is my code fragment:
    int[] length = new int[1];
    length[0] = 4;
    LineStripArray lsa = new LineStripArray (4, LineArray.COORDINATES, length);
    try{
    //Try create a set of points to connect all of sphere
    Point3f[] connectPoint = {
    new Point3f(0.063f, 0.85f, 0.099f),//1
    new Point3f(0.083f, 0.81f, 0.02f),//2
    new Point3f(0.083f, 0.84f, 0.04f),//3
    new Point3f(0.085f, 0.91f, 0.03f)};
    for (int i = 0; i<connectPoint.length; i++)
    lsa.setCoordinate(i, connectPoint);
    Thread.currentThread().sleep(500);
    System.out.println("Count line No. " + i );
    }//Try block
    catch(InterruptedException ie){
    }//Catch block
    Appearance lineApp = new Appearance();
    lineApp.setColoringAttributes(green);
    Shape3D linelsa = new Shape3D(lsa, lineApp);
    linelsa.setUserData("lsa");
    tg.addChild(linelsa);Edited by: kklam on Apr 2, 2008 6:28 AM

  • JDK 1.6 on Solaris. Multiple java processes and thread freezes

    Hi, we've come across a really weird behavior on the Solaris JVM, reported by a customer of ours.
    Our server application consists of multiple threads. Normally we see them all running within a single Java process, and all is fine.
    At some point in time, and only on Solaris 10, it seems that the main Java process starts a second Java process. This is not our code trying to execute some other application/command. It's the JVM itself forking a new copy of itself. I assumed this was because of some JVM behaviour on Solaris that uses multiple processes if the number of threads is > 128. However at the time of spawn there are less than 90 threads running.
    In any case, once this second process starts, some of the threads of the application (incidentally, they're the first threads created by the application at startup, in the first threadgroup) stop working. Our application dumps a list of all threads in the system every ten minutes, and even when they're not working, the threads are still there. Our logs also show that when the second process starts, these threads were not in the running state. They had just completed their operations and were sleeping in their thread pool, in a wait() call. Once the second process starts, jobs for these threads just queue up, and the wait() does not return, even after another thread has done a notify() to inform them of the new jobs.
    Even more interesting, when the customer manually kills -9 the second process, without doing anything in our application, all threads that were 'frozen' start working again, immediately. This (and the fact that this never happens on other OSes) makes us think that this is some sort of problem (or misconfiguration) specific to the Solaris JVM, and not our application.
    The customer initially reported this with JDK 1.5.0_12 , we told them to upgrade to the latest JDK 1.6 update 6, but the problem remains. There are no special JVM switches (apart from -Xms32m -Xmx256m) used. We're really at a dead end here in diagnosing this problem, as it clearly seems to be outside our app. Any suggestion?

    Actually, we've discovered that that's not really what was going on. I still believe there's a bug in the JVM, but the fork was happening because our Java code tries to exec a command line tool once a minute. After hours of this, we get a rogue child process with this stack (which is where we are forking this command line tool once a minute):
    JVM version is 1.5.0_08-b03
    Thread t@38: (state = IN_NATIVE)
    - java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) @bci=168980456 (Interpreted frame)
    - java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) @bci=0 (Interpreted frame)
    - java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) @bci=62, line=53 (Interpreted frame)
    - java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) @bci=182, line=65 (Interpreted frame)
    - java.lang.ProcessBuilder.start() @bci=112, line=451 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) @bci=16, line=591 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) @bci=69, line=429 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String) @bci=4, line=326 (Interpreted frame)
    - java.lang.Thread.run() @bci=11, line=595 (Interpreted frame)There are also several dozen other threads all with the same stack:
    Thread t@32: (state = BLOCKED)
    Error occurred during stack walking:
    sun.jvm.hotspot.debugger.DebuggerException: can't map thread id to thread handle!
         at sun.jvm.hotspot.debugger.proc.ProcDebuggerLocal.getThreadIntegerRegisterSet0(Native Method)
         at sun.jvm.hotspot.debugger.proc.ProcDebuggerLocal.getThreadIntegerRegisterSet(ProcDebuggerLocal.java:364)
         at sun.jvm.hotspot.debugger.proc.sparc.ProcSPARCThread.getContext(ProcSPARCThread.java:35)
         at sun.jvm.hotspot.runtime.solaris_sparc.SolarisSPARCJavaThreadPDAccess.getCurrentFrameGuess(SolarisSPARCJavaThreadPDAccess.java:108)
         at sun.jvm.hotspot.runtime.JavaThread.getCurrentFrameGuess(JavaThread.java:252)
         at sun.jvm.hotspot.runtime.JavaThread.getLastJavaVFrameDbg(JavaThread.java:211)
         at sun.jvm.hotspot.tools.StackTrace.run(StackTrace.java:50)
         at sun.jvm.hotspot.tools.JStack.run(JStack.java:41)
         at sun.jvm.hotspot.tools.Tool.start(Tool.java:204)
         at sun.jvm.hotspot.tools.JStack.main(JStack.java:58)I'm pretty sure this is because the fork part of the UnixProcess.forkAndExec is using the Solaris fork1 system call, and thus all the Java context thinks all those threads exist, whereas the actual threads don't exist in that process.
    It seems to me that something is broken in UnixProcess.forkAndExec in native code; it did the fork, but not the exec, and this exec thread just sits there forever. And of course, it's still holding all the file descriptors of the original process, which means that if we decide to restart our process, we can't reopen our sockets for listening or whatever else we want to do.
    There is another possibility, which I can't completely rule out: this child process just happened to be the one that was fork'd when the parent process called Runtime.halt(), which is how the Java process exits. We decided to exit halfway through a Runtime.exec(), and got this child process stuck. But I don't think that's what happens... from what I understand that we collected, we see this same child process created at some point in time, and it doesn't go away.
    Yes, I realize that my JVM is very old, but I cannot find any bug fixes in the release notes that claim to fix something like this. And since this only happens once every day or two, I'm reluctant to just throw a new JVM at this--although I'm sure I will shortly.
    Has anyone else seen anything like this?

  • Platform.runLater messes up my Thread.currentThread().getContextClassLoader()

    Hi,
    I have a plugin mechanism in my application. The plugins are defines by an interface and are loaded via URLClassLoader. A plugin can also have resources, loaded via ResourceBundle.getBundle.
    Whenever a plugin's method is called, I do this, before it is called:
    ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(pluginClassLoaders.get(pluginClass.cast(proxy)));
    // Invoke plugin method
    Thread.currentThread().setContextClassLoader(oldLoader);
    The plugin methods are called in their own thread, that means, when I want to open a window I need to do it on the JavaFX Application Thread with Platform.runLater.
    The problem is, that in the run method of the Platform.runLater, my Thread.currentThread().getContextClassLoader() is not my URLClassLoader but the Application Classloader.
    Why I need this?
    I don't want the plugin developer to always keep in mind, that he has to pass the correct class loader (of his classes) into the ResourceBundle.getBundle method.
    Instead I thought I could rely on Thread.currentThread().getContextClassLoader(), which is set in the main application, to load the correct bundle.
    It would work, but not if I load the bundle inside the JavaFX Application Thread (but which makes the most sense for UI development).
    So my goal was to have a convenient method like:
    String getResource(String bundle, String key)
    return ResourceBundle.getBundle(bundle).getString(key),  Thread.currentThread().getContextClassLoader());
    To avoid passing the classloader every time.
    Any ideas on this?

    OK, found the problem.
    In data-sources.xml, there is a connection pool and a managed-data-source settings. If I set the data source in there - it works!! Seems these XML tags take preference above the datasource tag.
    This is how the data-sources.xml now looks that's been working:
    <?xml version = '1.0' standalone = 'yes'?>
    <data-sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/data-sources-10_1.xsd" schema-major-version="10" schema-minor-version="1">
    <connection-pool name="jdev-connection-pool-MYDB">
    <connection-factory factory-class="com.mysql.jdbc.Driver" user="henkie" password="->DataBase_User_recGxQcVfghwCszzy_gfsRgwOrxutL2l" url="jdbc:mysql://localhost/mydb"/>
    </connection-pool>
    <managed-data-source name="jdev-connection-managed-MYDB" jndi-name="jdbc/MYDBDS" connection-pool-name="jdev-connection-pool-MYDB"/>
    </data-sources>

  • Thread.currentThread().getContextClassLoader().getResourceAsStream() bug?

    Hello
    I have a problem with Thread.currentThread().getContextClassLoader().getResourceAsStream() sporadically returning null when my app is running via JNLP using Win XP/build 1.6.0_20-b02 and tomcat 6-20/JnlpDownLoadServlet.
    The code is:
    final InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);I have added a map that counts the number of non null streams returned by getResourceAsStream. Here is the output when running with tracing level 5:
    cache: Reading Signers from 1024 http://x.x.x.x:8080/MDA/webstart/VTSDBClient-SOK.jar | C:\Users\xxx\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\61\6b90d63d-4feb6af0-1.7-SNAPSHOT-.idx
    cache:  Read manifest for http://10.10.20.64:8080/MDA/webstart/VTSDBClient-SOK.jar: read=117 full=14269
    cache: Reading Signers from 1024 http://x.x.x.x:8080/MDA/webstart/VTSDBClient-SOK.jar | C:\Users\xxx\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\61\6b90d63d-4feb6af0-1.7-SNAPSHOT-.idx
    Weird! data/eez-de.shp has been loaded 77 time(s) previously but is now null
    Loader is com.sun.jnlp.JNLPClassLoaderSo getResourceAsStream managed to open the file 77 times before it suddenly returns null.
    From the trace it looks like it happens when the cache is doing " Reading Signers from 1024 ..." the second time for VTSDBClient-SOK.jar. Could it be related to bug 6911763 (http://bugs.sun.com/view_bug.do?bug_id=6911763)?
    What causes the cache to reread the Signers in general and is there a way to provoke it?
    Thanks
    Carsten

    Just a tad more info on this.
    Each time Thread.currentThread().getContextClassLoader().getResourceAsStream() returns null there is a:
    network: SyncFileAccess.openLock: handled OverlappingFileLockException, remainint TO : 10000in the log.
    My does does spawn multiple threads that accesses different resources located in the same jar file in the client. Could it be a problem with using Thread.currentThread().getContextClassLoader().getResourceAsStream() from multiple threads and a slow respose from the JNLPDownLoadServlet and some locking scheme used by the JNLP cache?
    cache: Reading Signers from 1024 http://x:8080/MDA/webstart/aislayer.jar | C:\Users\x\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\52\5e675934-678dbaa9-1.5-SNAPSHOT-.idx
    BinaryFile: trying to figure out how to handle [3] data/eez-dk.shp
    cache: Reading Signers from 1024 http://x:8080/MDA/webstart/aislayer.jar | C:\Users\x\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\52\5e675934-678dbaa9-1.5-SNAPSHOT-.idx
    BinaryFile: trying to figure out how to handle [3] data/eez-se.shp
    cache: Reading Signers from 1024 http://x:8080/MDA/webstart/aislayer.jar | C:\Users\x\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\52\5e675934-678dbaa9-1.5-SNAPSHOT-.idx
    BinaryFile: trying to figure out how to handle [3] data/12nm.shp
    cache: Reading Signers from 1024 http://x:8080/MDA/webstart/aislayer.jar | C:\Users\x\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\52\5e675934-678dbaa9-1.5-SNAPSHOT-.idx
    BinaryFile: trying to figure out how to handle [3] data/eez-pl.shp
    cache: Reading Signers from 1024 http://x:8080/MDA/webstart/aislayer.jar | C:\Users\x\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\52\5e675934-678dbaa9-1.5-SNAPSHOT-.idx
    BinaryFile: trying to figure out how to handle [3] data/danm_nav.shp
    BinaryFile: trying to figure out how to handle [3] data/europ_nav.shp
    BinaryFile: trying to figure out how to handle [3] data/eez-de.shp
    network: SyncFileAccess.openLock: handled OverlappingFileLockException, remainint TO : 10000

  • IOException and Threads

    Hello everybody,
    I have the following problem, I have a typical consumer and producer situation, and the producer read a String via the CommConnection and write this String in a RecordStore. The consumer takes this String and sends it via http to a server, this work fine. There is one Thread:     
    ioReader = new Thread(this);
    ioReader.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while (ioReader == thisThread)
    try
    CommConnection cc = (CommConnection)
    catch (IOException e) {   }
    There is the second Thread:     
    sendHttp = new Thread(this);
    sendHttp.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while (sendHttp == thisThread)
    try
    HttpConnection connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
    catch (IOException e) {   }
    and the Main Thread.
    My Problem is, when the sendHttp can not call a server, he block the other two threads for 10 second before he throw an IOException. In the end this thread blocked the whole system, because the idea is, that he should try to sending again and again.
    Thanks for every answer

    You need to setup a worker class that extends Thread and then have its run() method implement the connectivity or whatever the task is. Look at this article
    http://developers.sun.com/techtopics/mobility/midp/articles/threading/
    Regs jP

  • Thread.currentThread() ); Meaning

    Does anyone know what the output I'm getting from the currentThread method means?
    What do the int(s) represent? I've checked the API, it doesn't go into detail about
    the return.
    Method Detail
    currentThread
    public static Thread currentThread()
        Returns a reference to the currently executing thread object.
        Returns:
            the currently executing thread.And here's what I'm doing :
    System.out.println("currentThread output : " + Thread.currentThread() );
    //OUTPUT
    Thread[Thread-1,5,main]Edited by: rico16135 on May 3, 2008 1:17 PM

    It's all there in the docs.
    Read Thread.currentThread's docs. It returns a reference to the Thread object for the currently running thread.
    System.out.println calls toString, so look at Thread's toString method.
    Also look at Thread's constructors.

  • Difference between Application.CurrentCulture and Thread.CurrentCulture

    Can someone tell me the difference between Application.CurrentCulture and Thread.CurrentCulture.
    Thread has CurrentCulture and CurrentUICulture. But Application has only CurrentCulture. Why?
    (https://msdn.microsoft.com/en-us/library/system.windows.forms.application.currentculture(v=vs.110).aspx)
    (https://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture(v=vs.110).aspx)

    1)
    Application.CurrentCulture delegates to Thread.CurrentThread.CurrentCulture("Gets or sets the culture information for the current thread") so it only sets it for the main thread of the
    application.
    2) They are both properties of a Thread object, which you can access via Thread.CurrentThread.
    CurrentCulture – Tells you the user’s current locale, as set in the Region
    applet.  I.e.: Where is the user located?
    CurrentUICulture – Tells you the native language of the version of Windows
    that is installed.  I.e.: What language does the user speak?
    The user can change CurrentCulture using the Region applet.  It’s used to determine formatting for numeric and date/time
    strings.
    Rachit
    Please mark as answer or vote as helpful if my reply does

  • URG & IMP: How does one stop the Thread.currentThread?

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to help.
    If I try Thread.currentThread.isAlive() post tehinterrupt, it doesnot work as desired and teh thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile varible to stop the thread as recommended by sun and since this is the currentThread, it cannot be assigned to null.
    Thanks
    Priya

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()Whyever would a thread want to deliver a stop() to itself.
    Did you mean that you wanted to stop() a different thread?
    As indicated in the (depreaction) documentation for stop(), using interrupt()
    is a better idea. However, that requires you to have a protocol
    where the receiver of the interrupt then reacts in an appropriate
    manner, i.e. interrupt() can be the basis for cooperative
    thread termination; it can't merely replace a stop() call
    in an existing application without any other changes.
    >
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to
    help.
    If I try Thread.currentThread.isAlive() post
    tehinterrupt, it doesnot work as desired and teh
    thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile
    varible to stop the thread as recommended by sun and
    since this is the currentThread, it cannot be
    assigned to null.Think about what you are trying to achieve. Did you want
    to just do a Throw() out of the current method, with (or
    without )a corresponding Catch() in some outer context)
    so that the you can unwind in case of an exceptional
    condition and have the thread exit?
    >
    Thanks
    Priya

Maybe you are looking for

  • Free application and charged

    Hi there, I would like to know why when I want to download an application which is FREE and I try to download it, I type my password and then, I'm charged in my credit card for it. I don't understand the reason of this cost if the app is for free!  I

  • Error when install Oracle XE in Ubuntu: invalid user && ...

    When I install Oracle XE in Ubuntu I got message from Terminal /bin/chown: `oracle:dba': invalid user /bin/chown: `oracle:dba': invalid user /bin/chmod: cannot access `/etc/init.d/oracle-xe': No such file or directory /var/lib/dpkg/info/oracle-xe-uni

  • Problem scrolling fonts in Illustrator CS4

    Hi- I've had issues from day 1 using AI CS4.  When I am deciding on a font style, I highlight the text, then click on the font type and scroll through the fonts.  Then I will encounter 2 problems: 1. Some fonts won't let me continue to scroll.  It st

  • Can we make the SELECTION CRITERIA BOX act as a Menu / Submenu system?

    Dear All, I have written several queries. For user convenience, I wish to combine all related queries in a single Query and use the Selection Criteria box as a Menu System to select which Query script to run. I can already do this by the use of varia

  • PR Release with respect to HR Org structure.

    Hi , I am having a requirnment where Business needs to Approve PR's based on the HR org struct and $ limit . Users maintained in HR org struct. have specifed roles ( eg. Managers , VP , Directors , CFO's)  & based on the $ limit in PR's they become