Threads & Methods

hi,
i have question.... when you call a method ... then are you creating a
new Process........ or in other words : is
calling a method = creating a new process
just curious

answer = no
A thread represents a flow of execution - when you call a method the same thread is used to run that method. When that method is finished the thread continues from where it was in the calling method.
I'm surprised you're asking this question given your areas of expertise. Perhaps I've misunderstood what you mean?
Hope this helps.

Similar Messages

  • Deprecated Thread Methods

    My organization has recently come from the Microsoft world into the J2EE world. In .Net, Microsoft has an abort method on threads that is similar to the Java's stop method. Unfortunately, the stop method has been deprecated.
    While I have read the information on why this method is dangerous, I don't understand why the method has been removed. If I have a situation that warrants killing a thread (such as in the case of an application server that hosts other threads of execution), why remove it from the platform? While I agree with Sun's article on seeking out alternative methods, there are still exceptions where a thread just needs to be interrupted so that it can get out of a deadlock, endless loop or blocking I/O.
    Since the stop method is deprecated, is there an equivalent VM call that I can interface from native code?
    I must say that I feel a bit like I'm being mothered by Sun.

    From your comments, you make a strong argument that suggests there's no need for a VM-level stop function.
    This puzzles me because operating systems implement kill methods to terminate rogue processes, yet they remain efficient and manage to keep things clean. Granted, multiple processes don't generally share memory structures but certainly the OS, on their behalf, shares memory structures. I'm puzzled as to why similar desires/features aren't present in the JRE.
    Regardless, short of running multiple JRE instances, each managing just one piece of work, the current deprecated status of the stop method renders Java without the ability to stop something that's gone wild unless the application is specifically pre-programmed to anticipate this behavior. (Of course that's a bit of a catch 22 in and of itself but...)
    There is also a subscription to the notion that my company or company x can write perfect software that never hangs a Java-based application server. I feel that this is impractical -- especially when what businesses ask of IT continues to get more complex.
    At this point perhaps it's fair to reveal the underlying reasons for my up-to-now, hypothetical questions. In my situation, company x is actually Sun. They failed to expose a socket timeout on their implementation of HTTPUrlConnection. I suppose that pretty much removes the luster from the argument that I, or anyone else, can write perfect software when the inventors of Java are themselves, imperfect. Of course, like you said and the JDK documents, the stop method will not abort a blocking socket read anyway (...although there's no reason why it couldn't except for more flawed design decisions...)
    I've certainly investigated alternative packages but I'm just chasing a moving target. HTTPUrlConnection today, class x tomorrow. That's why I was wanting something at the framework level to provide a trap door so that recovery without terminating the JRE is possible.

  • Start Thread method behaviour

    I'm using Oracle 10
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining optionsI created two Java classes and a wrapper procedure.
    1. The first class timeOutSAPEntry has a delay caused by sleep method of 10 sec. then updates a row in table sap_entry.
    2. The second class createMonitorSAPEntry creates an instance of timeOutSAPEntry, call start() method and ends.
    3. And the wrapper procedure just calls createMonitorSAPEntry.
    My problem: when I call the wrapper procedure, it hangs for 10 sec (consequence of sleep method). But, I expected that the thread could be created, started and then the control returns to procedure and finishes immediatelly. You can see in the execution below the sysdate before and after the procedure call.
    Is there any solution? I would like the same behaviour of others JVM, where the main thread continues the execution and not hangs out waiting for the started thread.
    create or replace
           and compile java source named "timeOutSAPEntry"
    as
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    public class timeOutSAPEntry
        extends Thread{
        public void run(){
            try{
                 this.sleep(10000);
                 Connection conn =
                        DriverManager.getConnection("jdbc:default:connection:");
                 PreparedStatement  st = conn.prepareStatement("update cmforna.sap_entry set status = 'Failed' where Status = 'Sent'");
                 st.executeUpdate();
                 st.close();
                 conn.commit();
                 conn.close();      
            }catch(Exception e){
                e.printStackTrace();
    create or replace
           and compile java source named "createMonitorSAPEntry"
    as
    public class createMonitorSAPEntry{
       public static void create(){
            timeOutSAPEntry to = new timeOutSAPEntry();
            to.start();
    create or replace procedure create_monitor_post
    as
    language java name 'createMonitorSAPEntry.create()';
    SQL> insert into sap_entry
      2  (id, posted_on, status)
      3  values
      4  (6, sysdate, 'Sent');
    1 row created.
    SQL>
    SQL> commit;
    Commit complete.
    SQL>
    SQL> select to_char(sysdate, 'hh24:mi:ss') Before_Time from dual;
    BEFORE_T
    16:27:04
    SQL>
    SQL> exec create_monitor_post;
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select to_char(sysdate, 'hh24:mi:ss') After_Time from dual;
    AFTER_TI
    16:27:14
    SQL> Many tks,
    Miguel

    Add a KeyAdapter like this:
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent ke) {
        int key = ke.getKeyCode();
        if (key == KeyEvent.VK_LEFT) x1--;
        if (key == KeyEvent.VK_RIGHT) x1++;
    });*Note that I added this just after the bouncing = true; ... which is on about line 33.
    **Note that you will need to click in the Applet before the keys will function.
    ***Note that you will also likely want to slow down the balls.
    ~Bill

  • Thread Methods but in Object class, y?

    Why wait, notify, notifyall methods are in object class instead of Thread class?

    thechad wrote:
    It's not clear to me why. Probably it's a historical artefact .. once it was in Object, it's hard to take it out.
    You're question is a fair question it seems to me. Maybe someone will tell you there's a good reason.Yes, there is a very good reason and it's not a historical artifact.
    wait / notify are used for locking in java. For instance, imagine you have a job queue, and you've got a whole bunch of worker threads that are getting jobs from it. What happens when the queue is empty and there are no more jobs? You want to wait for the queue to have more jobs. Then when a new job comes in, you want to notify any thread waiting that it can now proceed.
    In fact, with reference to why isn't this just handled in thread, it is dangerous and wrong to call wait, notify or notifyall on a Thread object... Thread.join calls wait on the thread and thread death calls notifyAll, but API docs don't guarentee this so you should avoid these methods in a Thread object.

  • Best thread method for a chat server

    What would be the best way to thread a chat server in Java? I understand threads, but I'm new to java. I'm just looking for links to the appropriate classes not code. I already have the send/receive methods planed, but I'm interested in the best ways to pool the clients once connected.

    class: Thread
    interface: Runnable
    The two items above are what you need.

  • Thread.run() method..

    I was wondering how the "Thread.run()" method get called. I started with "Thread.start()" and found it calls the "Thread.start0()" which is a native method.
    I downloaded the JDK 5 source code and went to "j2se\src\share\native\java\lang\Thread.c". In "Thread.c" I found a mapping of "start0()" with "JVM_StartThread".
    After that I opened the "hotspot\src\share\vm\prims\jvm.cpp". From line no 2257 to 2316 I saw the implementation of "JVM_StartThread".
    In side "JVM_StartThread", I saw there is a call to "Thread::start(native_thread)" and opened the "hotspot\src\share\vm\runtime\Thread.cpp". In "Thread.start()" method there is a call to "os::start_thread(thread);".
    In "hotspot\src\share\vm\runtime\os.cpp" the "os::start_thread()" calls the "pd_start_thread(thread);" method. But I did not get the "pd_start_thread(thread);" method in os.cpp.
    Note: I am java programmer and hardly understand the C/C++ languages. But had a doubt how the run() method get called and how the Thread.start() method works. But I got stuck here.
    Kindly help me to know how the flow goes, when we call the Thread.start() and how the run() method is linked to it.

    But I did not see anything in the os.cpp. In fact i did not find the "pd_start_thread(thread);" .
    void os::start_thread(Thread* thread) {
      // guard suspend/resume
      MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
      assert(thread->is_baby_thread(), "thread has started");
      thread->clear_is_baby_thread();
      OSThread* osthread = thread->osthread();
      // A thread may be suspended in the presence of the profiler.
      // Only start thread when it's not suspended.
      osthread->set_state(RUNNABLE);
      if (!thread->is_vm_suspended()) {
        pd_start_thread(thread);
    }

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

  • How to display a modal message while processing in a thread.

    I have difficulty in display a modal dialog while in processing in a background.
    I have created the following class.
    package fedex.screen.component;
    import java.awt.*;
    // This infobox is a modal dialog which display static text and stay
    // on screen without blocking proceeding code from execution and can
    // only close by issuing close method.
    public class ProcessInfoBox implements Runnable
         // Display dialog box
         private InfoBox dialog = null;
         // Thread to enable showing of Dialog Box
         private Thread thread = new Thread(this);
         // Determine if to close dialogbox
         private boolean isFinish = false;
         public ProcessInfoBox(Frame frame) {
              dialog = new InfoBox(frame,"Performing Operation","Processing...");
    thread.setPriority(Thread.MAX_PRIORITY);
         public void setTitle(String title) {
              dialog.setTitle(title);
         public void setText(String text) {
              dialog.getMessageLbl().setText(text);
         // The reference return will be ProcessInfoBox.InfoBox
         public InfoBox getInfoBox() {
              return dialog;
         // Thread method
         public void run() {
              dialog.setVisible(true);
              // If true return from thread and exit.
              while ( isFinish == false )
                   try
                        Thread.sleep(500); // 500 msec
                   catch ( InterruptedException e )
         // Start showing dialog
         final public void show() {
              thread.start();
              isFinish = false;
         final public void hide() {
              isFinish = true;
              dialog.setVisible(false);
         // Dialog box which show text.
         public class InfoBox extends Dialog
              private Label messageLbl = new Label("Processing ...");
              public InfoBox(Frame frame, String title, String message) {
                   super(frame,title,true);
                   initInfoBox();
              public Label getMessageLbl() {
                   return messageLbl;
              private void initInfoBox() {
                   setLayout(new BorderLayout());
                   add(messageLbl,BorderLayout.CENTER);
                   setSize(250,150);
    FormUtility.centerForm(this);
         public static void main(String[] args) {
              Frame frame = new Frame("BigMac");
              frame.setSize(600,600);
              frame.setVisible(true);
              ProcessInfoBox box = new ProcessInfoBox(frame);
              box.show();
              for ( int i = 1; i < 10000; i++ )
                   System.out.println(i);
              box.hide();
    To test the code I used the following section to test
    The main method in the class is used. In the simple
    example, the message did correctly update itself while
    i is increment. However, when I try on more complex
    application, the message just stalk there without
    updating itself as it is hanging.
    I have try to set piority to highest but without effect.
    Is there anything to rectify the situation
    thank

    The "please wait" dialog is a modal dialog. When u
    show it, the following code can not executed!
    That's the problem

  • "Portable" way to do message passing between threads?

    (I posted this on the Apple Developer Forums already, but since that forum is only accessible to registered and paid iPhone developers, I thought it would be nice to put it here as well so as to get some more potential eyeballs on it. I apologize if this kind of "cross-posting" is not kosher/is frowned upon around here.)
    Hey everybody,
    "Long-time listener, first-time caller," heh.
    I've been working for the past 2-3 months on my very first iPhone app. Actually, what I've been working on is a framework that I plan to use in an iPhone app of my own but which I am also trying to write for the "lowest-common-denominator" so that I (and others) can use it in other apps written for both Mac and iPhone.
    Not only is this my first time writing an iPhone app, it is my first time writing for any Apple platform. In fact, it is my first time using Objective-C, period. I cannot stress this enough: I am a "n00b." So go easy on me. I also have not worked with threading before this, either, on any platform, so the learning curve for me here is rather significant, I'm afraid. I am NOT afraid of either taking the time to learn something properly OR of rolling up my shirtsleeves and working. However, on account of my experiences so far, I am finding myself (not to flame or anything!) quickly becoming frustrated by and disillusioned with not so much Objective-C itself, but the Foundation frameworks.
    So with that said, read on, if you dare...
    The basic idea behind my project is that the framework I am writing will present an API to developers which will allow them to write client apps that interact with a particular network appliance or network-aware embedded system. I already have my basic set of classes up and functioning, and the framework works to my satisfaction both on MacOS and iPhoneOS. The platforms I am targeting are MacOS X Tiger 10.4 and later, and iPhoneOS, and up until this point, I've managed to keep a codebase that works on all of the above.
    What I wanted to do next was add some multithreaded goodness to the mix. (Woe is me.) I have asynchronous network socket I/O working within the main thread, and it, in fact, works a treat. In my test app on the phone, I've managed to keep the UI nice and responsive by using the main thread's runloop efficiently. But even though TCP async I/O works fine within the main thread, I want to be able to split out and offload the processing of any data received by the app from the appliance to its own thread. (It is possible, and even desirable, for an application using this framework to be connected to multiple appliances simultaneously.)
    My idea, in order to try to keep things as simple and as clean as possible, was to implement a wrapper class that presented my other main class as an "actor." So, rather than instantiating my main class, one would create an instance of the wrapper class which would in turn control a single instance of my main class and spawn its own thread that the network connection and all data processing for that particular connection would run within.
    (I hope I'm making sense so far...)
    Out of the gate, writing a subclass of NSThread sounds like the logical design choice for an "actor-type" thread, but because I was trying to maintain Tiger compatibility, I stuck with +detachNewThreadSelector:etc.
    Once I decided to pursue the actor model, though, the main problem presented itself: how to best pass messages between the main thread and all of the "actor" threads that might be spawned?
    I stumbled upon -performSelector:onThread:withObject:, and knew instantly that this was exactly what I was looking for. Unfortunately, it doesn't exist on Tiger; only its much more limited little brother -performSelectorOnMainThread:withObject: does. So I kept looking.
    All of the pre-Leopard documentation, tutorials, and sample code that I read indicated that to pass messages between threads, I needed to basically pretend that the threads were separate processes and use the expensive Distributed Objects mechanism to get messages back and forth. Unfortunately, even if that WAS a desirable option, iPhoneOS does not have any support for DO! Grrr...
    Finally, I thought I found the answer when I ran into a third-party solution: the InterThreadMessaging library from Toby Paterson (available @ http://homepage.mac.com/djv/FileSharing3.html). In this library, the author basically implemented his own version of -performSelector:onThread:withObject: called -performSelector:withObject:inThread:. Sounds close enough, right? And actually, it is pretty darn close. It's made to do exactly what it sounds like, and it does it in a platform-neutral way that works on pre-Leopard systems as well as iPhoneOS, using Mach ports instead of DO.
    (...wellll, ALMOST. I discovered after I built a small test app around it that it actually isn't "iPhone-clean." The author used an NSMapTable struct and the NSMap*() functions, which don't exist in iPhoneOS, and he also implemented the handlePortMessage delegate method, but although iPhoneOS has NSPort, it DOESN'T have NSPortMessage. GAAARGH. So I took the time to replace the NSMapTable stuff with NSValue-wrapped objects inside of an NSMutableDictionary, and replaced the handlePortMessage method implementation with a handleMachMessage method, which took some doing because I had to figure out the structure of a Mach message, NO thanks to ANY of the available documentation...)
    Once I started using it, though, I quickly discovered that this implementation wasn't up to snuff. My "actor" class and my main thread will be passing a ton of messages to each other constantly whenever there is network activity, and with InterThreadMessaging, I found that whenever activity started to ramp up, it would collapse on itself. This mostly took the form of deadlocks. I found a note that someone else wrote after experiencing something similar with this library (quoted from DustinVoss @ http://www.cocoadev.com/index.pl?InterThreadMessaging):
    "It is possible to deadlock this library if thread A posts a notification on thread B, and the notification on B causes a selector or notification to be posted on thread A. Possibly under other circumstances. I have resolved this in my own code by creating an inter-thread communication lock. When a thread wants to communicate, it tries the lock to see if another thread is already using the InterThreadMessaging library, and if it can't get the lock, it posts a message to its own run-loop to try again later. This is not a good solution, but it seems to work well enough."
    So I tried implementing what he described using a global NSLock, and it did help with some of the deadlocks. But not all. I believe the culprit here is the Mach ports system itself (from the NSPortMessage documentation for -sendBeforeDate:):
    "If the message cannot be sent immediately, the sending thread blocks until either the message is sent or aDate is reached. Sent messages are queued to minimize blocking, but failure can occur if multiple messages are sent to a port faster than the portís owner can receive them, causing the queue to fill up."
    InterThreadMessaging in fact calls -sendBeforeDate: and exposes the deadline option, so I tried setting a really short time-to-live on the Mach messages and then intercepted any NSPortTimeoutExceptions that were thrown; upon catching said exceptions, I would then re-queue up the message to be sent again. It worked, but Performance. Was. A. Dog. At least the message queue wouldn't be full indefinitely anymore, causing the main thread to block, but during the whole time that these messages were expiring because the queue was full and then being re-queued, either the main thread was trying to send more messages or the actor thread was trying to send more messages. And as far as I can tell, the Mach ports queue is global (at the very least, there is seemingly only one per process). The message would get through with this model...eventually.
    JUST IN CASE the problem happened to be something I screwed up as I was rewriting portions of the InterThreadMessaging library so that it would compile and work on the iPhone SDK, I substituted in the original version of the library in my Mac test app to see if any of these problems became non-issues. I found that both versions of the library -- mine and the original -- performed identically. So that wasn't it.
    Finally, in frustration I said, "screw it, I'm going to try it the Leopard way," and replaced all of the method calls I was making to InterThreadMessaging's -performSelector:withObject:inThread: with calls to Foundation's native -performSelector:onThread:withObject: instead, changing nothing else within my code in the process. And wouldn't you know: IT WORKED GREAT. Performance was (and is) fantastic, about on-par with the non-threaded version when only dealing with a single connection/instance of my class.
    So, in the end, I was able to do nothing to salvage the InterThreadMessaging implementation of cross-thread method calling, and as far as I can tell, I'm out of (good) options. And thus my mind is filled with questions:
    How is the Leopard -performSelector:onThread: method implemented? I'm guessing not using Mach ports, given that I didn't have the same blocking & deadlocking problems I had with InterThreadMessaging. Is it possible to re-implement this Leopard+ method in a similar manner as a category to NSObject under Tiger? Or is it possible, perhaps, to increase the size of the Mach ports queue so that InterThreadMessaging works at a sane level of performance? Or -- I'm getting desperate here -- is there any way that I could trick -performSelectorOnMainThread: to target a different thread instead? (I am assuming here that -performSelectorOnMainThread is implemented under-the-hood much like the new -performSelector:onThread: is implemented, but with a hard-coded NSThread pointer built-in to the code, and that the new method just exposes a more flexible interface to what is basically the same code. I'm probably wrong...) Is there another third-party library out there that I've missed that fits my requirements for being able to do message-passing between threads in an efficient and portable manner?
    I refuse to believe that there is no way for me to maintain compatibility with all of the platforms I wish to support without having to resort to making preprocessor #ifdef spaghetti out of my code. And there SURELY has to be a better way of doing cross-thread message passing in Tiger without using Distributed Objects, for Pete's sake! Is this really how people did it for years-on-end since the dawn of NeXT up until the advent of Leopard? And if there really, genuinely wasn't another alternative, then what is up with the lack of DO in iPhoneOS?? Does Apple seriously intend for developers who have good, solid, tested and working code to just chuck it all and start over? What if there was some aspect of DO that previous implementations relied upon that cannot be recreated with simple -performSelector:onThread: calls? (I don't know what those aspects would be...just a hypothetical.) I mean, I can understand needing to write new stuff from scratch for your UI given how radically different the interface is between the Mac and iPhone, but having to reimplement back-end guts such as something as elemental as threads...really?!
    I do laud the inclusion of the new method in Leopard as well as the new ability to subclass NSThread itself. But for those of us that need to support Tiger for one reason or another, some of these restrictions and omissions within iPhoneOS seem like rather pointless (and frustrating) roadblocks.
    As I hope is obvious here, I have tried to do my homework before throwing up my hands and pestering y'all. If you have the patience to deal with me, please tell me what I am missing.
    Thanks for taking the time to read,
    -- Nathan

    Thanks again for your patience. Comments below.
    etresoft wrote:
    It is pretty unusual that anyone would want to call perfomrSelector on any thread other than the main thread.
    What I described in my original post was not a worker thread, but an "actor."
    It is hard for me to answer this question because there are so many options available to do "message passing". The fact that you think there are so few tells me that you really aren't sure what you need to use.
    I didn't say there were few options for message passing. I said there were few options for message passing that fit my criteria, which are that any potential solutions should both A) work efficiently and with good performance, and B) be available both pre-Leopard AND on the iPhone. -performSelector: ain't available before Leopard. Distributed Objects is overkill. Kernel Mach messages apparently have a high overhead, too, as my experience with the third-party library I wrote about in my original message shows.
    ...consider notifications.
    I thought notifications couldn't be posted across threads, either. How do I post a notification to another thread's default notification center or notification queue from a different thread?
    The notification center is owned by the process. Each run loop can listen for just the notifications it wants. You don't "pass" or "send" notifications, you run then up the flagpole for all to see.
    I am aware of how to use notifications. The documentation for NSNotificationCenter clearly states that "In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself."
    So, again, I don't see how one thread can post a notification in such a way that the observer's registered method is executed in another thread (posting notifications "across threads"). This probably isn't a big deal if you are using mutexes (assuming you don't actually care which thread carries out the task associated with the notification posting), but as I said before, this is not what I'm after.
    I don't know what you are really after.
    Allow me to attempt to explain a second time, in a more concise fashion.
    My app will have multiple, persistent TCP connections open, one connection per remote device. The user will be able to select a task to execute on a particular device that we have a connection open to, and get back from the application real-time updates as to the progress or results of the execution of that task. In certain cases, the length of the task is infinite; it will keep executing forever and sending back results to my application which will update its display of the results every second that ticks by until the user STOPS that particular task.
    This can be done simply using async I/O in the main runloop, sure. But if I were going to thread this so that I could be processing the results I've received back from one *or more* remote devices while also doing something else, given that I will only have one (persistent) connection open to any given remote device that I'm interacting with (that is to say, I won't be opening up a separate TCP session for every single task I want to execute on a single device simultaneously), it makes sense _to me_ to implement this as I've described: with every connection to each remote device getting its own thread that lasts for the lifetime of the TCP session (which could be the entire time the application is running, times however many devices the user wishes to be connected to while in the app). I won't be spawning a new thread for every task the user wishes to ask a remote device to do.
    This is why (I think) I need bi-directional messaging between the main thread and each of these threads dedicated to a given remote device that we have an active session with/connection to. The main thread needs to be able to tell remote device X (which already has a running thread dedicated to it) to do task A, and then get real-time feedback from that remote device so that the main thread can be displaying it to the user as it is coming back. Same with remote device Y running task B, simultaneously. At any time during the execution of these tasks, the user needs to be able to tell my app to stop one of these tasks, and the main thread needs to send that message to one of the remote devices via that device's dedicated thread.
    This is why I am talking about this in terms of the "actor model," and not the "worker thread model," because the former model seems to fit what I want to do.
    -- Nathan

  • Find out how many threads in a Java program

    Why do I get ID 20, ID 21, ID 22 by runing the following code? I would like to know if i acturely create a thread then stop it probably. somehow i need to call it two more times in my program.
    start() and interrrupt() are default thread methods. when I call start() it goes to my run() method. I am worry about if the thread 20 and 21 are still doing something after creating thread 22
    main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;
            main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;
            main = new Thread(this);
            System.out.println("ID " + main.getId());
            main.start();
            main.interrupt();
            main = null;

    Here is my code, I would like to know if I implement my threads nicely here, I am worrying those threads are still alive, they should be interrupted. but why I got different thread ID, when i resume it?
    // Two player board game play in turn. Human plays first as red, the computer plays
    // second as blue. I used thread here for repainting the applet, because the computer
    // evaulation function is quite slow, the gui won't draw human player's move until it
    // finishs calculating computer's move. the solution i use is interrupting the current
    // thread, let the gui repaint before calculating the computer move.
    // Board.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends Canvas implements Runnable, MouseListener {
        private Thread main;
        private int state = 0;
        private double aMove = 0;
        public void init() {
            addMouseListener(this);
        public void run() {
            removeMouseListener(this);
            main.interrupt();
            main = null;
            repaint();
            // calculate computer's move, then making move
            // this is a slow evalution function goes here
            for (int i = 0; i <10000000; i++) {
                aMove = Math.pow(0.1,1000000000);
            state = 1;
            repaint();
            System.out.println("Blue makes a move on postion " + aMove);
            state = -1;
            addMouseListener(this);
        public void paint(Graphics g) {
            System.out.println("paint");
            if (state == 1) {
                g.setColor(Color.blue);
                g.fillOval(0, 0, 20, 20);
            if (state == -1) {
                g.setColor(Color.red);
                g.fillOval(0, 0, 20, 20);
        public void mouseReleased(MouseEvent e) {
            // human player makes a move on postion 0;
            aMove = 0;
            System.out.println("Red makes a move on postion " + aMove);
            state = -1;
            repaint();
            // Why the following gives me different thread here every time?
            main = new Thread(this);
            System.out.println("Thread ID: "+ main.getId());
            main.start();
        public void mousePressed(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mouseClicked(MouseEvent e) {
    // appletdemo.java
    import java.applet.*;
    import java.awt.*;
    public class appletdemo extends Applet{
        Board b = new Board();
        public void init() {
            System.out.println("start ");
            setLayout(new BorderLayout());
            this.add(b);
            b.init();
            setVisible(true);
    }

  • Get the current thread

    Hello,
    Thread suspension is an important operation for get the thread stack information�s (i.e. local variables...). JPDA provide three ways to suspend threads ThreadReference.suspend(),VirtualMachine.suspend(),or through events by setSuspendPolicy(int policy) method which suspend threads to the requested event occurs in the target VM.
    But, how can I know the current thread after Threads vm suspensions?
    By events we can deduce it, when MethodEntryEvent occur in the target vm through thread () method.
    But, what about the others tow Thread suspension methods?
    For example:
    //after suspension through vm.suspend().
    Virtual machine vm =�;
    List Threads = vm.allThreads();This list Returns a list of the currently running threads. But I don�t find any method to know which the current thread from this list is? �The index or the name of this current thread�.
    Later, what is the difference between ThreadReference.suspend (), VirtualMachine.suspend ().which one is preferable for suspend a running application, then extract the state of the current thread and save it in an object,for restoring its state later?
    please i need an answer,
    regards.

    You need a profiler. I can't recommend any, but do a google search.

  • Problem in modal method (decision workitem)

    Hi,
    I'm with a problem during the execution of a decision workitem. I've set a method to run before it (the modal execution) and, within it, called a transaction (in the case PA30) but it call the transaction two times.
    How can I make it execute only one time?
    Thanks in advance.
    -h

    When I searched the forum I found [this thread|Methods of Workitem execute twice;. Maybe it helps you also?
    Regards,
    Martin

  • Trouble rationalizing use of multi-threading in run of the mill servlets

    Hey everybody,
    While spending time writing an internal wiki article on servlets for work, I asked myself a very basic question: What does multi-threading buy average servlets where the business logic requires procedural handling of the request?
    Don't get me wrong: I appreciate the fact that servlet containers spawning a new thread being less expensive than spawning an entirely new process is helpful and efficient. Coming from a background in PHP, it is great how servlets maintain persistence. However, as more of my coworkers are required to gain proficiency in Java and designing servlets, it is a question that many will ask and aside from having real-time processing of data files and other arduous tasks, I cannot think of any instances of where multi-threading benefits the application.
    What are some of the ways that you are using multi-threading with web applications?
    How would you explain why and where you would want to use multi-threading to someone?
    Thank you in advance for your insight,
    Andy

    how can we pass arguments to the run ()method?Create classes which implement Runnable that take your runtime parameters as constructor arguments and store them.
    eg: if your single thread method is   static void foo (int quantity, String name) {
        for (int i=0; i<quantity; i++) {
          System.out.println(name);
    // caller code
      foo(7, "wombats");Then you can make a runnable implementation thus:public class Foo implements Runnable {
      final int quantity_;
      final String name_;
      public Foo (int quantity, String name) {
        quantity_ = quantity;
        name_ = name;
      public void run () {
        for (int i=0; i<quantity_; i++) {
          System.out.println(name_);
    // caller code
      new Thread(new Foo(7, "wombats")).start();
    You could overload this method to take parameters in
    your class that implements the Runnable interface,
    and then call the base run() method.I don't get what you mean by this; Runnable is an interface so there is no base class run() method, and a run() overloaded with extra parameters method wouldn't get called by the thread.
    Pete

  • Executing Code outside of the Event Dispatcher Thread

    Hello,
    I have just come to learn that any actionPerformed() method that is called after an event occurs actually runs in the Event Dispatcher. So, for example, if you click on a button, any code that is run as a result is run in the event dispatcher.
    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread? Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    My questions are a result of this: How does one normally go about updating a GUI during a long process? I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?

    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread?
    Correct. So if your response to an action is, for example, creating a new bit of UI using data which is already in memory, you can just do it.
    Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    You will need to create a new thread: method calls are just control flow within the same thread.
    You should use an object which implements Runnable and then use "new Thread(foo).start()"
    My questions are a result of this: How does one normally go about updating a GUI during a long process?
    You have to hop back onto the EDT whenever an update is required. I'd suggest writing yourself a little reusable class or two to help you with this - such as a listener mechanism with an implementation which handles the thread hopping.
    I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?
    Yes.
    Should I use inner classes? I would prefer to keep them as separate classes within the same package.
    Depends on all sorts of things - sometimes anonymous or declared inner objects are the way forward, sometimes public class objects, sometimes generic helper objects and sometimes utility classes. There are all sorts of different scenarios. As I say, though, it's worth writing some utility/helper classes to reuse. Personally I don't find SwingWorker is ideal so I have my own. Note that an abstract Action implementation is a very useful one, since this is precisely where you need to be doing most of the thread hopping.

  • Parallel function call and thread issue

    Sorry to post one issue here which is related to code. i was debugging a code which was wrote long time back by one developer. the issue is two function is called parallel using thread and one function set a variable true at end and another function just
    looping until the variable is set to true. the variable value is not getting set to true. here i am posting a code snippet and just tell me what is mistake in the code for which variable is not getting set to true by first function.
    when user click button then two function is invoked
    private void UPDATE_Click(object sender, System.EventArgs e)
    SavedFirst();
    AddCheckThread();
    public void SavedFirst()
    IsOpen = true;
    System.Threading.Thread loadT = new System.Threading.Thread(new System.Threading.ThreadStart(SaveAll));
    loadT.Start();
    IsOpen = false;
    private void AddCheckThread()
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(addCheck));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    private void SaveAll()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(AddProducts));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    return;
    private void AddProducts()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into the Database?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    if (comboOUR.SelectedItem == null || comboCountry.SelectedItem == null || comboSelleble.SelectedItem == null || txtOereff.Text == "" || txtUKPrice.Text == "" || txtUSPrice.Text == "" || txtSUrCharge.Text == "" || txtOURUS.Text == "" || txtOURUK.Text == "")
    FormValidation();
    else
    Gather_Data();
    bool isInserted = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into \"Detailed-Product\" Too?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    isInserted = bbaProduct.BBASaveProduct();
    if (isInserted == true)
    isInserted = false;
    isInserted = bbaProduct.InsertInProductTable(BBAProduct.DetailProductID);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Product Successfully Added ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    isInserted = bbaProduct.InsertInProductTable(0);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Successfully Inserted Into the database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Process Cancelled By The User", "Add");
    ALLFlag = true;
    return;
    #region Add Check
    private void addCheck()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    this.Opacity = 0.8;
    axShockwaveFlash1.Visible = true;
    axShockwaveFlash1.Play();
    while (!ALLFlag)
    int x = 0;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.StopPlay();
    this.Opacity = 1;
    ALLFlag = false;
    loadingThread.Abort();
    return;
    help me to locate where is the mistake for which ALLFlag value is not getting set to true. thanks

    Your reliance on a field value across threads isn't going to work reliably.  In a multi-core/multi-threaded world the memory model allows for reading data out of order for optimization reasons.  Additionally the CPU can and will cache recently
    used data in memory that isn't shared across processors.  This can get you into trouble as you will not be reading the same value across processors.
    The only correct way to ensure that multiple threads access the same data correctly is to use sync objects that are designed for that such as a Semaphore or Mutex.  Sync objects allow you to safely share data across threads.
    Overall your code appears to be trying to update the UI using a thread but since it is calling Invoke each time you are basically spawning a thread that then blocks waiting for the UI thread.  You could pretty much eliminate your issues by getting rid
    of the threading calls altogether along with any sort of state management variables that were arbitrarily created (ALLflags) and simply use BeginInvoke.  You didn't post who was calling your higher level save methods but if it is a UI element then BeginInvoke
    and InvokeRequired are completely redundant as is all the threading.
    You can cleanly update this code to eliminate all the extra variables and threading and simply use the newer async/await functionality to help resolve the issues your code is having.  But you still have problems with the invoked code.  In one of
    the methods you are looping while waiting for a variable to be set.  But since you invoked it then it is occurring on the UI thread.  Because it is on the UI thread and that can only do 1 thing at a time, if ALLflag is false your code will deadlock. 
    The only other code that would set it to true cannot run because it is also invoked on the UI thread and only one of them can run at any one time.  Basically each of your threads are going to try to run on the same thread and only 1 of them will be able
    to.  Until the first thread method finishes the second one will never run.
    If you need Boolean flags then consider using a ManualResetEvent instead.  It is thread safe, works across threads and doesn't have any of the problems of a Boolean field when talking about threading. But you still have a deadlock between your invoked
    code that nothing will solve except rewriting your code.
    Michael Taylor
    http://blogs.msmvps.com/p3net

Maybe you are looking for

  • Exchange calendar invitations accepted in IOS remain "new" in iCal

    My work calendar and email is based on Exchange. I manage both from a Mac (using Outlook 2011 for Mac) and an iPhone 5 running IOS 7.latest. It works just fine. If I accept an invitation on any platform is is accepted on all. Then I look at OSX Calen

  • Safari Version 6.1.6 (7537.78.2) become unresponsive.

    Safari Version 6.1.6 (7537.78.2) become unresponsive. I cannot access most websites and have to use Chrome now. I'm running iMac 24" early 2009 model with OSX 10.7.5. can anybody help? thank you!

  • Can't open sequence: " operation not allowed.  Out of memory"

    I have a project with several sequences. The master sequence started freezing on me. I restarted FCP and the computer, but now it won't let me open this sequence. It will let me open others in the project, but not this one. It's even smaller than oth

  • Change icons in App Package?

    I downloaded CandyBar 3 to check it out and was disappointed to find it no longer had App Extras. This was a way to change what icon an app put on it's documents, for instance I changed all zips and dmgs to cool black icons. I did some checking and f

  • Hot to select last month sales using fiscal calendar

    Hi All, I have the following query listed below select DISTINCT -1, vODS_GLBalance_test.Page, vODS_GLBalance_test.FiscalYearId, vODS_GLBalance_test.FiscalMonthOfYearId, GLAmount From ODS.Staging.vODS_GLBalance_Test Left Outer Join Ods.JJill.tODS_GLBa