Runnable a thread?

Is a class that implements Runnable itself a thread?
When i invoke run() method of a class that implements Runnable does it behave like a thread?
Or only Runnable object wrapped by Thread class is a Thread?

Is a class that implements Runnable itself a thread?Implementing Runnable is another way of writing threads, if you implement runnable you dont need to extend Thread, as a matter of fact it is considered the better way for writing threads. But thats another discussion
>
When i invoke run() method of a class that implements
Runnable does it behave like a thread?
use start
class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         public void run() {
             // compute primes larger than minPrime
PrimeRun p = new PrimeRun(143);
     new Thread(p).start();

Similar Messages

  • Runnable Vs Thread Class

    Hello All,
    I have a doubt regarding Runnable and Thread class. As we all know Java provides two ways to run Threads. One way is to extend Thread class and the other way is to implement Runnable Interface.
    Apart from the OOPS funda, does java have any other concept in providing two ways to run threads ?. I mean, we very well know that if we extend Thread class, we may not be able to extend any other class in Java . So if we implement Runnable interface,we can extend or implement any other Interface or class. Apart from this reason, does Java has any other concept in providing two ways to run threads ??
    Please share your knowledge
    Thanks and Have a Nice Day,
    Regds,
    Sai

    As far as I know, that's the only reason for the two options--one gives you flexibility in your class hierarchy, the other saves you a few lines of code. Personally, I always implement Runnable. The few lines of code saved seem trivial to me compared to "cleaner" OO (IMHO), but maybe somebody else has a better reason to extend Thread.

  • $ in classname of runnable classes (threads)

    I have an applet with a runnable subclass so that I can do processing in a thread rather than during paint.
    This works fine but when compiling it generates a ".class" file with a $ in the name.
    My main class is S2. The runnable subclass is "r". Compile generates S2.class and S2$r.class.
    That's not a problem natively (on window 98) but I want to upload the classes to my ISP (@home) webspace.
    Unfortunately, they do not allow $ in a file name.
    Can I get javac to create the subclass in a file without the $ ?

    I have an applet with a runnable subclass so that I
    can do processing in a thread rather than during
    paint.
    This works fine but when compiling it generates a
    ".class" file with a $ in the name.
    My main class is S2. The runnable subclass is "r".
    Compile generates S2.class and S2$r.class.
    That's not a problem natively (on window 98) but I
    want to upload the classes to my ISP (@home)
    webspace.
    Unfortunately, they do not allow $ in a file name.
    Can I get javac to create the subclass in a file
    without the $ ?I do not believe it is possible to do eliminate the '$' fro inner class names. An alternative is to package the applet and its associated classes in a .jar. This eliminates the problem and can greatly improve applet load times.
    Chuck

  • Diff bet Runnable and Thread

    Hi All,
    What is the major difference between Implementing Runnable interface and Extending Thread ?
    Thnx

    When you implement runnable, you can do nifty things like ... THIS:
    class Test implements Runnable {
         public static void main(String[] argv) {
              while( true ) new Thread(new Test()).start();
         public void run() {
              int i = 0;
              while( true ) {
                   i++;
                   System.out.print(i);
    }

  • Implementing Runnable interface  Vs  extending Thread class

    hi,
    i've come to know by some people says that Implementing Runnbale interface while creating a thread is better option rather than extending a Thread class. HOw and Why? Can anybody explain.?

    Its the same amount of programming work...
    Sometimes it is not possible to extend Thread, becuase your threaded class might have to extend something else.
    The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
    http://developerlife.com/lessons/threadsintro/default.htm#Implementing

  • Naming a thread that is created implementing Runnable

    How could I name a thread that I create using Runnable Interface?
    public class Test {
         * @param args the command line arguments
        public static void main(String[] args) {
            TestRunnable tr = new TestRunnable();
            /* running thread */
            new Thread(tr).start();//THREAD 3
    public class TestRunnable implements Runnable {
        public void run() {
            for(int y = 1; y < 1000; y++) {
                System.out.println("3333333333333333333333333333333333333333 " + Thread.currentThread() );
    }

    well, I'm just experimenting; learning about Threads. As you can see I
    was able to name the other two threads, I was just curious how you would do it,
    using the Runnable Interface, seeing as those two naming options I used don't
    seem to be an option for it. I may be misunderstanding your reply...
        public static void main(String[] args) {//thread 0
            FrameThread ft = new FrameThread();//extends Thread
            ft.setName("ft");
            Thread td = new Thread("td") {
                @Override
                public void run() {
                    for(int a = 1; a < 1000; a++) {
                        System.out.println("1111111111111111111111111111111111111111 " + Thread.currentThread() );
            TestRunnable tr = new TestRunnable();//class implements Runnable
            /* running threads */
            td.start();//THREAD 1
            ft.start();//THREAD 2
            new Thread(tr).start();//THREAD 3
    }I'm naming them so when I use : Thread.currentThread() the return slot has the name I provide.
    Edited by: rico16135 on May 3, 2008 3:14 PM
    Edited by: rico16135 on May 3, 2008 3:17 PM

  • Java Bouncing Balls Threads problem?

    Hello,
    I am working on a homework assignment to represent a java applet with some bouncing balls inside. So far so good. The balls bounce and behave as they are supposed. The only thing is that I want to make 2 buttons, Start and Stop (this is not part of the assignment, but my free will to provide some extra stuff :) ) . I am implementing Runnable for the animation and ActionListener for the buttons. I did research on threading, but somehow I am still not getting quite the result I want. The applet is not displaying my buttons (I guess I am not implementing them correctly) and I dont know whether I have synchronized the threads correctly as well. So, I am asking for some guidance how can I do this? Thanks in advance!
    As a remark, I am new to Java, as I am just starting to learn it and this is my first assignment.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    public class Balls extends JApplet implements Runnable, ActionListener
         Thread runner = null;     
         Image img;
        Graphics gr;          
        BallCollision ball[];
        Balls can;
        JButton stopButton;
        JButton startButton;
        JPanel controls;
        boolean stop,start;
        //field for 10 balls
        static final int MAX=10;
         public void init()
              setSize(800,600);
              img = createImage(size().width,size().height);
              gr = img.getGraphics();     
              startButton = new JButton("Start");
              stopButton = new JButton("Stop");
              stopButton.addActionListener(this);
              startButton.addActionListener(this);
              controls = new JPanel();
              controls.setLayout(new FlowLayout());
              controls.add(startButton);
              controls.add(stopButton);
              //new Thread(this).start();
              ball = new BallCollision[MAX];
              int w=size().width;
              int h=size().height;          
              //creation of balls, which have different coordinates,
              //speed, direction and colors
              ball[0] = new BallCollision(w,h,50,20,1.5,7.5,Color.orange);
            ball[1] = new BallCollision(w,h,60,210,2.0,-3.0,Color.red);
            ball[2] = new BallCollision(w,h,15,70,-2.0,-2.5,Color.pink);
            ball[3] = new BallCollision(w,h,150,30,-2.7,-1.0,Color.cyan);
            ball[4] = new BallCollision(w,h,210,30,2.2,-12.5,Color.magenta);
              ball[5] = new BallCollision(w,h,360,170,2.2,-1.5,Color.yellow);
              ball[6] = new BallCollision(w,h,210,180,-1.2,-2.5,Color.blue);
              ball[7] = new BallCollision(w,h,330,30,-2.2,-1.8,Color.green);
              ball[8] = new BallCollision(w,h,180,220,-2.2,-1.8,Color.white);
              ball[9] = new BallCollision(w,h,330,130,-2.2,9.0,Color.gray);     
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == startButton) start = true;
                   can.start();
              if(e.getSource() == stopButton) start = false;
                   can.stop();
         public void start()
              if (runner == null)
                   runner = new Thread (this);
                   runner.start();
         public void stop()
              if (runner != null)
                  runner.stop();
                    runner = null;
         public void run()
              while(true)
                   try {Thread.sleep(15);}
                     catch (Exception e) { }               
                   //move our balls around
                   for(int i=0;i<MAX;i++)
                        ball.move();
                   handleCollision();
                   repaint();     
         boolean collide(BallCollision b1, BallCollision b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //the distance between 2 colling balls' centres is
              //calculated by the theorem of Pythagoras
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.diameter)
                   return true;          
                   return false;     
         private void handleCollision()
              //ecah ball is checked for possible collisions
              for(int i=0;i<MAX;i++)
                   for(int j=0;j<MAX;j++)
                             if(i!=j)
                                  if(collide(ball[i], ball[j]))
                                       ball[i].hit(ball[j]);
                                       ball[j].hit(ball[i]);
         public void update(Graphics g)
              paint(g);
         public void paint(Graphics g)
              gr.setColor(Color.black);
              gr.fillRect(0,0,size().width,size().height);          
              //paint the balls
              for(int i=0;i<MAX;i++)
                        ball[i].paint(gr);          
              g.drawImage (img,0,0, this);                    
    class BallCollision
         int width, height;
         int diameter=30;
         //balls' coordinates and values to be incremented for directions
         double x, y, xIncremented, yIncremented, coll_x, coll_y;
         boolean collide;
         Color color;
         Graphics g;
         //constructor
         public BallCollision(int w, int h, int x, int y, double xInc, double yInc, Color c)
              width=w;
              height=h;
              this.x=x;
              this.y=y;
              this.xIncremented=xInc;
              this.yIncremented=yInc;          
              color=c;          
         public double getCenterX() {return x+diameter/2;}
         public double getCenterY() {return y+diameter/2;}
         public void move()
              if (collide)
                   double xvect=coll_x-getCenterX();
                   double yvect=coll_y-getCenterY();
                   if((xIncremented>0 && xvect>0) || (xIncremented<0 && xvect<0))
                        xIncremented=-xIncremented;
                   if((yIncremented>0 && yvect>0) || (yIncremented<0 && yvect<0))
                        yIncremented=-yIncremented;
                   collide=false;
              x+=xIncremented;
         y+=yIncremented;
              //if the ball reaches a wall, it bounces to the opposite direction
         if(x<1 || x>width-diameter)
              xIncremented=-xIncremented;
                   x+=xIncremented;
              if(y<1 || y>height-diameter)
                   yIncremented=-yIncremented;
                   y+=yIncremented;
         public void hit(BallCollision b)
              if(!collide)
                   coll_x=b.getCenterX();
                   coll_y=b.getCenterY();
                   collide=true;
         public void paint(Graphics graphics)
              g=graphics;
              g.setColor(color);
              //the coordinates in fillOval have to be int, so we cast
              //explicitly from double to int
              g.fillOval((int)x,(int)y,diameter,diameter);

    well i didnt arrive at this point without reading tutorials and researching.... sometimes other people can spot your mistakes a lot easier than you can, that's why I asked for help. 10x anyway for the interest!

  • What is the diffrence between My Runnable Interface and Java Runnable

    Hi folks
    all we know that interfaces in java just a decleration for methods and variables.
    so my Question is why when i create an interface its name is "Runnable" and i declared a method called "run" inside it.then when i implements this interface with any class don't do the thread operation but when i implement the java.lang.Runnable the thread is going fine.
    so what is the diffrence between My Runnable Interface and Java Runnable?
    thnx

    Hi folks
    all we know that interfaces in java just a decleration
    for methods and variables.
    so my Question is why when i create an interface its
    name is "Runnable" and i declared a method called
    "run" inside it.then when i implements this interface
    with any class don't do the thread operation but when
    i implement the java.lang.Runnable the thread is going
    fine.
    so what is the diffrence between My Runnable Interface
    and Java Runnable?
    thnxClasses and interfaces are not identified by just their "name", like Runnable. The actual "name" the compiler uses is java.lang.Runnable. So even if you duplicate the Runnable interface in your own package, it's not the same as far as the compiler is concerned, because it's in a different package.
    Try importing both java.util.* and java.awt.* (which both have a class or interface named List), and then try to compile List myList = new ArrayList();

  • Large Memory Usage and Frozen [thread dump attached]

    Hi,
    SQL Developer (Version 2.1.1.64, WinXP Pro, Java 1.6, Oracle 10g R2) always uses at least 550MB of memory, if left open, for more than a day, it invariably goes up to 700-800MB.
    If I close all windows and connections, virtually no memory is reclaimed.
    I clicked + beside a view to see the columns, sqldeveloper froze for a few minutes, below is the thread dump.
    2010-05-21 11:31:58
    Full thread dump Java HotSpot(TM) Client VM (14.2-b01 mixed mode):
    "CONNECTION_ALIVE" prio=6 tid=0x3891c000 nid=0x1d58 waiting for monitor entry [0x3a55f000]
    java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.T4CConnection.doPingDatabase(T4CConnection.java:3398)
    - waiting to lock <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.jdbc.driver.PhysicalConnection.pingDatabase(PhysicalConnection.java:7074)
    at oracle.javatools.db.ora.BaseOracleDatabase.isConnectionAlive(BaseOracleDatabase.java:165)
    at oracle.javatools.db.AbstractDatabase$1.run(AbstractDatabase.java:316)
    at java.lang.Thread.run(Thread.java:619)
    "Loading Children" prio=6 tid=0x3891bc00 nid=0x12c4 waiting on condition [0x39d5f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x03eab570> (a java.util.concurrent.FutureTask$Sync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:747)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:905)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1217)
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:218)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$IdeTaskTracker.run(RaptorTaskManager.java:532)
    at java.lang.Thread.run(Thread.java:619)
    "pool-2-thread-57" prio=6 tid=0x3891b400 nid=0x2094 waiting on condition [0x35b5f000]
    java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x09b819f0> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireNanos(AbstractQueuedSynchronizer.java:841)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireNanos(AbstractQueuedSynchronizer.java:1160)
    at java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:416)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1334)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1319)
    at oracle.dbtools.raptor.utils.Connections.lock(Connections.java:1306)
    at oracle.dbtools.raptor.navigator.xml.AbstractItemInstance.lockConnection(AbstractItemInstance.java:52)
    at oracle.dbtools.raptor.navigator.xml.XmlNodeInstance.listChildren(XmlNodeInstance.java:55)
    at oracle.dbtools.raptor.navigator.ObjectNodeFilter$ObjectNodeFilterLoadTask.doWorkImpl(ObjectNodeFilter.java:78)
    at oracle.dbtools.raptor.navigator.DeferredLoadingFilter$FilterLoadTask.doWork(DeferredLoadingFilter.java:124)
    at oracle.dbtools.raptor.navigator.DeferredLoadingFilter$FilterLoadTask.doWork(DeferredLoadingFilter.java:113)
    at oracle.dbtools.raptor.backgroundTask.RaptorTask.call(RaptorTask.java:193)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$RaptorFutureTask.run(RaptorTaskManager.java:492)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    "pool-2-thread-55" prio=6 tid=0x38d68400 nid=0xd74 runnable [0x3a15f000]
    java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at oracle.net.ns.Packet.receive(Packet.java:239)
    at oracle.net.ns.DataPacket.receive(DataPacket.java:92)
    at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:172)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:117)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:92)
    at oracle.net.ns.NetInputStream.read(NetInputStream.java:77)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1023)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:999)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:584)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:785)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:860)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3381)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3425)
    - locked <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1490)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.openResultSet(ResultSetTableModel.java:412)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.fetchNext(ResultSetTableModel.java:169)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:556)
    at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:540)
    at oracle.dbtools.raptor.backgroundTask.RaptorTask.call(RaptorTask.java:193)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$RaptorFutureTask.run(RaptorTaskManager.java:492)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    "AWT-EventQueue-0" prio=6 tid=0x354fac00 nid=0x18d4 waiting for monitor entry [0x3a45f000]
    java.lang.Thread.State: BLOCKED (on object monitor)
    at oracle.jdbc.driver.PhysicalConnection.getMetaData(PhysicalConnection.java:3891)
    - waiting to lock <0x09ad05f8> (a oracle.jdbc.driver.T4CConnection)
    at oracle.dbtools.raptor.plscope.Query.getToolTipText(Query.java:58)
    at oracle.dbtools.raptor.phighlight.TooltipPlugin$1.getToolTipText(TooltipPlugin.java:29)
    at oracle.ide.ceditor.CodeEditor.getToolTipText(CodeEditor.java:1734)
    - locked <0x17245f98> (a java.util.ArrayList)
    at oracle.javatools.editor.BasicEditorPane.getToolTipText(BasicEditorPane.java:1530)
    at javax.swing.ToolTipManager$insideTimerAction.actionPerformed(ToolTipManager.java:658)
    at javax.swing.Timer.fireActionPerformed(Timer.java:271)
    at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    "Background Parser" prio=6 tid=0x38a43400 nid=0x23c4 waiting on condition [0x39c5f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "SwingWorker-pool-5-thread-1142" prio=6 tid=0x38868800 nid=0x1a7c waiting on condition [0x3820f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x0e77bc10> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x38a76c00 nid=0x1d18 waiting on condition [0x3a35f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x387e2800 nid=0xd00 waiting on condition [0x3a25f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Background Parser" prio=6 tid=0x38752000 nid=0x2794 waiting on condition [0x39e5f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "Swing-Shell" daemon prio=6 tid=0x367f0000 nid=0xd7c waiting on condition [0x3a85f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x1069d0d8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Win32ShellFolderManager2.java:458)
    at java.lang.Thread.run(Thread.java:619)
    "Persistence Auto Flusher" daemon prio=6 tid=0x388a5c00 nid=0x1950 in Object.wait() [0x37e0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x0e892d48> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Thread-76" prio=6 tid=0x387aec00 nid=0x259c runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "WeakDataReference polling" prio=2 tid=0x38752800 nid=0xe94 in Object.wait() [0x3a05f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x0b6ba260> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at oracle.ide.util.WeakDataReference$Cleaner.run(WeakDataReference.java:88)
    at java.lang.Thread.run(Thread.java:619)
    "Image Animator 3" daemon prio=4 tid=0x3861b400 nid=0x2330 waiting on condition [0x3978f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at sun.awt.image.GifFrame.dispose(GifImageDecoder.java:653)
    at sun.awt.image.GifImageDecoder.produceImage(GifImageDecoder.java:230)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    "Background Parser" prio=6 tid=0x38348800 nid=0x978 waiting on condition [0x3988f000]
    java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at oracle.dbtools.raptor.plsql.BackgroundParser$1.construct(BackgroundParser.java:112)
    at oracle.dbtools.raptor.utils.NamedSwingWorker$2.run(NamedSwingWorker.java:115)
    at java.lang.Thread.run(Thread.java:619)
    "TextBufferScavenger" prio=6 tid=0x38324800 nid=0x1af0 in Object.wait() [0x3968f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x09bb9158> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at oracle.ide.model.TextNode$FacadeBufferReference$PollingThread.run(TextNode.java:1949)
    "pool-4-thread-1" prio=6 tid=0x36960400 nid=0x1a84 waiting on condition [0x35a5f000]
    java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x08150a78> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1963)
    at java.util.concurrent.DelayQueue.take(DelayQueue.java:164)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "IconOverlayTracker Timer" prio=6 tid=0x38520c00 nid=0x1b48 in Object.wait() [0x3950f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x0795f290> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Timer queue for AWT thread" daemon prio=6 tid=0x369b4000 nid=0x1f20 in Object.wait() [0x3940f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x077e1358> (a java.lang.Object)
    at java.lang.Object.wait(Object.java:485)
    at ice.util.awt.TimedAWTExecutor.nextElem(TimedAWTExecutor.java:108)
    - locked <0x077e1358> (a java.lang.Object)
    at ice.util.awt.TimedAWTExecutor.runScheduler(TimedAWTExecutor.java:130)
    at ice.util.awt.TimedAWTExecutor$1.run(TimedAWTExecutor.java:19)
    "WaitCursor-Timer" prio=6 tid=0x367c3c00 nid=0x1010 in Object.wait() [0x37b0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x077e1400> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "Native Directory Watcher" prio=2 tid=0x368d4000 nid=0x2334 runnable [0x3830f000]
    java.lang.Thread.State: RUNNABLE
    at oracle.ide.natives.NativeHandler.enterWatcherThread(Native Method)
    at oracle.ide.natives.NativeHandler$2.run(NativeHandler.java:252)
    at java.lang.Thread.run(Thread.java:619)
    "BaseTreeExplorer.NodeOpeningExecutor" prio=6 tid=0x3684b000 nid=0x8b0 waiting on condition [0x3810f000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x06950af0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:358)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    "Scheduler" daemon prio=6 tid=0x36846400 nid=0x14bc in Object.wait() [0x37f0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at oracle.dbtools.raptor.backgroundTask.TaskLinkedList.takeNextTask(TaskLinkedList.java:47)
    - locked <0x06950c70> (a oracle.dbtools.raptor.backgroundTask.TaskLinkedList)
    at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$SchedulerThread.run(RaptorTaskManager.java:422)
    "TimerQueue" daemon prio=6 tid=0x36832800 nid=0x88c in Object.wait() [0x37d0f000]
    java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at javax.swing.TimerQueue.postExpiredTimers(TimerQueue.java:218)
    - locked <0x06950da8> (a javax.swing.TimerQueue)
    at javax.swing.TimerQueue.run(TimerQueue.java:234)
    - locked <0x06950da8> (a javax.swing.TimerQueue)
    at java.lang.Thread.run(Thread.java:619)
    "ChangeSetService" prio=2 tid=0x367fd400 nid=0x2754 in Object.wait() [0x37c0f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x06892cc0> (a oracle.jdevimpl.vcs.changeset.ChangeSetService)
    at java.lang.Object.wait(Object.java:485)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.awaitEvents(ChangeSetService.java:178)
    - locked <0x06892cc0> (a oracle.jdevimpl.vcs.changeset.ChangeSetService)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.eventLoop(ChangeSetService.java:199)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService.access$200(ChangeSetService.java:56)
    at oracle.jdevimpl.vcs.changeset.ChangeSetService$2.run(ChangeSetService.java:138)
    at java.lang.Thread.run(Thread.java:619)
    "TimedCache-Timer" daemon prio=6 tid=0x35d52c00 nid=0x2448 in Object.wait() [0x3624f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.util.TimerThread.mainLoop(Timer.java:483)
    - locked <0x062ab118> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "JarIndex Timer" daemon prio=6 tid=0x35556400 nid=0x2488 in Object.wait() [0x35d4f000]
    java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.util.TimerThread.mainLoop(Timer.java:509)
    - locked <0x062206e0> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:462)
    "AWT-Windows" daemon prio=6 tid=0x354dd000 nid=0x1d0c runnable [0x3595f000]
    java.lang.Thread.State: RUNNABLE
    at sun.awt.windows.WToolkit.eventLoop(Native Method)
    at sun.awt.windows.WToolkit.run(WToolkit.java:291)
    at java.lang.Thread.run(Thread.java:619)
    "AWT-Shutdown" prio=6 tid=0x354a1800 nid=0x268c in Object.wait() [0x3585f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:259)
    - locked <0x062208d8> (a java.lang.Object)
    at java.lang.Thread.run(Thread.java:619)
    "Java2D Disposer" daemon prio=10 tid=0x354b7400 nid=0x5f4 in Object.wait() [0x3575f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x06220968> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at sun.java2d.Disposer.run(Disposer.java:125)
    at java.lang.Thread.run(Thread.java:619)
    "Low Memory Detector" daemon prio=6 tid=0x00ee1000 nid=0x2664 runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x00edc000 nid=0x1f6c waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Attach Listener" daemon prio=10 tid=0x00eda800 nid=0x206c runnable [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x00ed9400 nid=0xf64 waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=8 tid=0x00ec6c00 nid=0x2348 in Object.wait() [0x34e7f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x061b0298> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
    "Reference Handler" daemon prio=10 tid=0x00ec5800 nid=0x2484 in Object.wait() [0x34d7f000]
    java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
    - locked <0x061b0320> (a java.lang.ref.Reference$Lock)
    "main" prio=6 tid=0x009f8000 nid=0x19e0 waiting on condition [0x00000000]
    java.lang.Thread.State: RUNNABLE
    "VM Thread" prio=10 tid=0x00ec1800 nid=0x22e0 runnable
    "VM Periodic Task Thread" prio=10 tid=0x00eec000 nid=0x2604 waiting on condition
    JNI global references: 5312
    Heap
    def new generation total 45376K, used 28499K [0x03080000, 0x061b0000, 0x061b0000)
    eden space 40384K, 67% used [0x03080000, 0x04af44c0, 0x057f0000)
    from space 4992K, 28% used [0x05cd0000, 0x05e30850, 0x061b0000)
    to space 4992K, 0% used [0x057f0000, 0x057f0000, 0x05cd0000)
    tenured generation total 604992K, used 364537K [0x061b0000, 0x2b080000, 0x2b080000)
    the space 604992K, 60% used [0x061b0000, 0x1c5ae548, 0x1c5ae600, 0x2b080000)
    compacting perm gen total 57344K, used 57260K [0x2b080000, 0x2e880000, 0x33080000)
    the space 57344K, 99% used [0x2b080000, 0x2e86b348, 0x2e86b400, 0x2e880000)
    No shared spaces configured.
    Edited by: mdaly on May 21, 2010 11:42 AM

    The cause of hang could be figured out from the thread dump.
    I have fixed that in development code. It was happening from PL/SQL editor trying to create tooltip which locked up the connection.
    I am not sure what would lead to memory bloat even if the tool is not in use. There could be memory leak from some component. I am investigating that.
    Suggest you to keep ObjectViewers, reports & PL/SQL editor closed when not in use.
    Have Sql Array Fetch Size preference to 50 if it's higher.
    Do not have auto-refresh for Report editor.
    Keep Sql History, Find Db Object, Snippets collapsed.
    See if that helps.
    -Raghu

  • How to use multiple threads and swing for displaying status/interaction

    I have a Swing-app which have to show progress and allow userinteraction for these tasks:
    * First:
    retrieve a list of IDs(String) from the database (single thread running)
    * Second:
    some work on the id-list and list written to hd (same thread as above)
    * Third:
    retrieve Objects (based on the id-list) from different sources (Multiple Threads are running)
    To show the status I have a JProgressBar (indeterminate while task1&2 running) and
    a JTextArea showing the current status (connect,retrieve list, sort, ...)
    When task3 is starting the JTextArea have to disappear and be replaced by a ScrollPane
    with an array of Labels/TextAreas showing the status of each thread.
    While theses threads are working, the ID-list will be consumed and the JProgressBar
    shows the remaining precentage of the hole progress.
    Everything is working so far (excepts UI :) , the problem(s) I have:
    I need the threads to interacts with the user through the ui. e.g: "Connection to db-xyz lost! reconnect?"
    But I don&#180;t know how to do this correctly.
    I think one way would be to send an event to the ui... but how?
    (the ui must know which thread is calling to unpause it after user answered)
    I know that threads should NOT change the swing(-container) - How do I notify the ui that a thread has a question?
    Since these threads are really time-consuming the UI is not updated frequently,
    how can I increase this? (perhaps using another thread-priority?)
    thanks for help!

    if/when your threads need to interact with the UI, they can create a Runnable & send it to SwingUtilities.invokeLater or invokeAndWait. This Runnable can popup a message to the user, and act on the choice of the user (reconnect, cancel, ...). This action could be something which "unpauses" the task thread.
    You may need to do synchronisation between the code in the Runnable & the Thread to which it is related - so the latter Thread knows when the user has made the choice.

  • Thread query.

    i have the program below. I want to add in the ability to input data from the keyboard and still run the current thread. What do i do? Do i set the current thread as a background thread, then create another thread to handle keyboard input?? How do i get them to run together??
    Any tips appreciated.
    N.
    import java.io.*;
    import java.util.*;
    public class EmailListener implements Runnable{
         private Thread task = null;
         public EmailListener(){
              if (task == null) {
                  task = new Thread(this, "Email");
                  task.start();
         public void run() {
              Thread myThread = Thread.currentThread();
             while (task == myThread) {
                   try{
                        EmailRetriver er = new EmailRetriver("nemo.compsoc.com","nduggan","christmas",2110,"[email protected]");
                        er.readMail();
                        er.sendMail();
                        er.close();
                   catch(Exception e){
                        e.printStackTrace();
                        task = null;
                  try {
                            Thread.sleep(10000);
                  } catch (Exception e){}
         public static void main (String args[]) throws Exception {
              System.out.println("Intelligent Text Procesor Email Client ");
              new EmailListener();
    }

    Ah the wonders of concurrent programming. You're probably going to want some resources on it. These things are a bit more involved then you first think. Doug Lea's book is a great place to start. http://java.sun.com/docs/books/cp/ go from there.
    -Spinoza

  • I would like to know the role of the each thread on coherence

    Help me.
    I would like to know the role of the each thread on coherence.
    There are too many kind of threads.
    Example ~
    GC Slave     GC Slave     RUNNABLE
    RMI TCP Accept-1972     RMI TCP Accept-1972     RUNNABLE
    Health Center trace subscriber     Health Center trace subscriber     RUNNABLE
    LT=0:P=342534:O=0:port=55170     LT=0:P=342534:O=0:port=55170     RUNNABLE
    Attach API wait loop     Attach API wait loop     RUNNABLE
    PacketListener1     PacketListener1     RUNNABLE
    PacketListener1P     PacketListener1P     RUNNABLE
    PacketListenerN     PacketListenerN     RUNNABLE
    Cluster|Member(Id=1, Timestamp=2013-04-05 10:45:44.655, Address=192.168.240.157:8088, MachineId=50044, Location=site:,machine:TMTEST-PC,process:5316, Role=CoherenceServer)     Cluster|Member(Id=1, Timestamp=2013-04-05 10:45:44.655, Address=192.168.240.157:8088, MachineId=50044, Location=site:,machine:TMTEST-PC,process:5316, Role=CoherenceServer)     RUNNABLE
    RT=0:P=342534:O=0:TCPTransportConnection[addr=192.168.240.157,port=55178,local=55170]     RT=0:P=342534:O=0:TCPTransportConnection[addr=192.168.240.157,port=55178,local=55170]     RUNNABLE
    Finalizer thread     Finalizer thread     RUNNABLE
    WT=10     WT=10     RUNNABLE
    main     main     TIMED_WAITING
    IpMonitor     IpMonitor     TIMED_WAITING
    Invocation:Management:EventDispatcher     Invocation:Management:EventDispatcher     TIMED_WAITING
    Invocation:Management     Invocation:Management     TIMED_WAITING
    DistributedCache     DistributedCache     TIMED_WAITING
    JMX server connection timeout 52     JMX server connection timeout 52     TIMED_WAITING
    RMI Scheduler(0)     RMI Scheduler(0)     WAITING
    Thread-6     Thread-6     WAITING
    stop JMX Server on shutdown     stop JMX Server on shutdown     WAITING
    Logger@9228429 3.7.1.7     Logger@9228429 3.7.1.7     WAITING
    PacketReceiver     PacketReceiver     WAITING
    PacketPublisher     PacketPublisher     WAITING
    PacketSpeaker     PacketSpeaker     WAITING
    WT=7     WT=7     WAITING
    WT=9     WT=9     WAITING
    -----------------------------------------------------------------------------------------------------------------------------------------------

    Briefly
    PacketListener1 PacketListener1P PacketListenerN - listening IO threads for TCMP transport protocol
    Cluster|Member(Id=1, Timestamp=2013-04-05 10:45:44.655, Address=192.168.240.157:8088, MachineId=50044, Location=site:,machine:TMTEST-PC,process:5316, Role=CoherenceServer) - main thread for cluster service (discovery, node joing / leave, etc)
    IpMonitor - IP monitor, participates in death detection scheme
    Invocation:Management:EventDispatcher - Event dispatch thread for distributed JMX service in Coherence
    Invocation:Management - main thread for distributed JMX service in Coherence
    DistributedCache - main thread for DistributedCache cache service
    Logger@9228429 3.7.1.7 - Coherence async logging thread
    PacketReceiver - Thread dispatching incomming network packets
    PacketPublisher - Thread sending out packets via TCMP
    PacketSpeaker - Thread sending out packets via TCMP (offloads some work from PacketPublisher for better core utilization)

  • Sharing variable across Threads created by ThreadFactory

    Hi,
    I am initializing an ExecutorService as:
    static ExecutorService service =
    Executors.newFixedThreadPool(16, new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    t.setContextClassLoader("<<My_Class_Loader");
    return t;
    Now, I have to initialize a service that should be initialized only once that all the Callables submitted to this ExecutorService can use. The variable needed to be shared across the Threads must have "My_Class_Loader" as its ContextClassLoader. How can I do that? Thanks in advance.

    Something like this:
    Thread t = new MyThread(r, ccl); // ccl = your context class loader
    public class MyThread extends Thread
      private MyVariable myVariable;
      public MyThread(Runnable r, ClassLoader ccl)
        super(r);
        this.setContextClassLoader(ccl);
        myVariable = ...; // your class loader stuff
      public MyVariable getMyVariable()
        return myVariable;
    // ... then runnables can go:
    ((MyThread)Thread.currentThread()).getMyVariable();

  • Thread pool library

    Hello all,
    Does anybody know an open-source library that provides a thread pool with the following behavior?
    When a task is submitted...
    if (there are idle threads in the pool) {
        use an idle thread to execute the task.
    } else {
        if (currentThreadCount < maximumPoolSize) {
            create new thread to execute the task.
        } else {
            put the task in the queue.
            (tasks in the queue will be processed when threads are available).
    }If a thread remains idle for X time, it dies.
    Thank you

    I ran your code and it ran it just fine, I prefixed your println to print out the currentTimeMillis to show it ran right after each other.
    System.out.println(System.currentTimeMillis() +  "{code}
    Here is the result:
    1244482518471 Starting main.
    1244482518483 Running a task
    Here is code fragments from ThreadPoolExecutor I generated my sudo code from.
    {code}
         * Executes the given task sometime in the future.  The task
         * may execute in a new thread or in an existing pooled thread.
         * If the task cannot be submitted for execution, either because this
         * executor has been shutdown or because its capacity has been reached,
         * the task is handled by the current <tt>RejectedExecutionHandler</tt>.
         * @param command the task to execute
         * @throws RejectedExecutionException at discretion of
         * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
         * for execution
         * @throws NullPointerException if command is null
        public void execute(Runnable command) {
            if (command == null)
                throw new NullPointerException();
            if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
                if (runState == RUNNING && workQueue.offer(command)) {
                    if (runState != RUNNING || poolSize == 0)
                        ensureQueuedTaskHandled(command);
                else if (!addIfUnderMaximumPoolSize(command))
                    reject(command); // is shutdown or saturated
         * Creates and starts a new thread running firstTask as its first
         * task, only if fewer than corePoolSize threads are running
         * and the pool is not shut down.
         * @param firstTask the task the new thread should run first (or
         * null if none)
         * @return true if successful
        private boolean addIfUnderCorePoolSize(Runnable firstTask) {
            Thread t = null;
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                if (poolSize < corePoolSize && runState == RUNNING)
                    t = addThread(firstTask);
            } finally {
                mainLock.unlock();
            if (t == null)
                return false;
            t.start();
            return true;
         * Rechecks state after queuing a task. Called from execute when
         * pool state has been observed to change after queuing a task. If
         * the task was queued concurrently with a call to shutdownNow,
         * and is still present in the queue, this task must be removed
         * and rejected to preserve shutdownNow guarantees.  Otherwise,
         * this method ensures (unless addThread fails) that there is at
         * least one live thread to handle this task
         * @param command the task
        private void ensureQueuedTaskHandled(Runnable command) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            boolean reject = false;
            Thread t = null;
            try {
                int state = runState;
                if (state != RUNNING && workQueue.remove(command))
                    reject = true;
                else if (state < STOP &&
                         poolSize < Math.max(corePoolSize, 1) &&
                         !workQueue.isEmpty())
                    t = addThread(null);
            } finally {
                mainLock.unlock();
            if (reject)
                reject(command);
            else if (t != null)
                t.start();
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Rather complicated (possibly!) threading/event handling problem...

    OK, so here's a good question to ask for my first post to this site!
    My current "project" is a GUI applet that does real-time interactions on a set of objects and user input. I'm using double buffering, event handling (from the keyboard) and multiple threads to handle the categories of "user input and graphics" and "world state updating." Here is a rough overview of how the program is layed out:
    // keyboard input status class
    class Keyboard extends KeyListener {
       static int[] code = new int[7];            // contains keycodes of interesting keys
       static boolean[] status = new boolean[7];     // status of keys (true=pressed)
       static boolean getStatus(int key) {
          return status[key];
       void keyPressed(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = true;
       void keyReleased(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = false;
    // main program applet
    class Program extends Applet implements Runnable {
       static Thread thread;      // main thread of applet
       static Image buffer;         // double buffer for offscreen rendering
       static boolean running;  // flag to indicate status of applet
       void init() {
          buffer = createImage(500, 500);
          // other initializations
       void destroy() {
          // other disposes
       void start() {
          running = true;
          thread = new Thread(this);
          thread.start();
          addKeyListener(new Keyboard());   // begin receiving input
       void stop() {
          running = false;
          if(thread != Thread.currentThread())
             thread.join();    // wait for thread to die before continuing
       void run() {
          double paintTimer = 0;   // timer to suspend painting to buffer until necessary
          double dt = 0;       // difference in time between loops
          while(running) {
             // update timing stuff (dt and paintTimer)
             // update world status
             paintTimer -= dt;      // to decrement painting timer
             if(paintTimer <= 0) {
                paintTimer = 1.0 / fps;    // reset paint timer based on current fps setting
                synchronized(syncObject) {
                   // paint world to buffer
                   repaint();
             Thread.yield();  // to yield time to painting and user input thread
       // this method is only called by the internal thread within the applet
       //  that is responsible for painting and event handling
       void paint(Graphics g) {
          // make sure painting to screen won't conflict with thread that's drawing on buffer!
          synchronized(syncObject) {
             g.drawImage(buffer, 0, 0, null);  // do double buffering...paint buffer to screen
    }So the end result is that it works fine some of the time, but every once in awhile I'll get these strange results where it'll seem as if the internal thread that handles graphics and input will get bogged down or stop responding normally, even with the Thread.yield() call from the main applet thread. I'll get results where the world will continue to be updated correctly, but the user input and onscreen rendering freeze in a particular state for a matter of seconds, and then it seems to regain control for a brief few milliseconds (hence I'll get a quick screen refresh and keyboard state change), and then it'll freeze again. Once this starts happening somewhere in the middle of execution, it continues to happen throughout that runtime session. Sometimes when I force-close the appletviewer I'll get weird native runtime exceptions that seem to occur within Sun's keyboard input manager.
    Almost always it'll run perfectly for many minutes, and then all of a sudden it'll start to freeze up. Every once in awhile it freezes almost immediately after startup. I've run some testcases on it and am pretty confident it has nothing to do with the synchronization or the fact that I create a new applet thread every time the applet is restarted dynamically. Is it something happening within the event thread of the applet that I'm not aware of? Or is it something wrong with the flow of my code? Thanks for any input or help you can give! I'll be happy to send more details if needed.
    Zach

    right before your repaint, putSystem.out.println("Is EDT? "+SwingUtilities.isEventDispatcherThread());if its printing false, then you need to do SwingUtilities.invokeLater( ... );
    and put GUI updating code in the invoke later.

Maybe you are looking for

  • Error while deleting UIElements from existing view of webdynpro project

    hiiii everybody, I have an existing project which i need to modify.so when i am trying to delete some UIElements from existing view and saving the metadata, itz showing error as for example: 1)Group Group2 header is missing 2)wdThis cannot be resolve

  • Change host name and url of Oracle Application

    Hello, I need help in changing the url of Oracle Application OLD url - http:// appssvr.XYZ.com:8007 NEW url - http://erp.XYZ.co.in:8002 Please help

  • IWeb Bug Report

    How do I fix this error? "There was an error with reading your iDisk quota" I have checked my Sys Prefs and the information is accurate and readable. I am able to see the usage space of my iDisk when I click on the iDisk tab. TIA Steve

  • Trying to unlock iPhone 4

    trying to unlock a iphone 4 with orange ive got the phone off mother in law she rang orange got an email confirming and said it would work today if followed instructions but when i connected to i tunes it said the carrier is not supported please help

  • Parameter based on formula question

    Post Author: mmishkin CA Forum: Formula I have a formula that calculates a date, I want to create a parameter based on this formula. When I go through adding a new parameter it only shows me my table fields and not my formulas. Can you make a paramet