Calling getAppletContext() from a working thread.

Hi guys,
I'm new to Java so all apologies if I'm asking a stupied question.
I have a simple applet that creates a working thread and I'm tring to call getAppletContext() from that thread.
Obviously my working thread has no instance of the Applet class so it fails.
I've try to create an instance of Applet, but I'm getting an error saying that the applet is not initialised.
This is my code:
class MyThread extends Thread
    String ThreadName;
    public MyThread(String threadName)
        ThreadName = threadName;
    @Override public void run()
        // ??? How to make the following line work ???
        getAppletContext().showDocument(new URL("javascript:alert(\"Calling from myThread\")"));
public class MyApplet extends Applet {
     public void init()
        // The following line works!
        getAppletContext().showDocument(new URL("javascript:alert(\"Calling from MyApplet)"));
        Thread WorkingThread = new MyThread("Thread1");                                                                
        WorkingThread.start();
}{code}
Please help,
Many thanks!
Salvador                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Got it.
I needed to pass the keyword this to the thread constructor and then use that....
Many thanks!

Similar Messages

  • Calling a delegate on the UI thread from a work thread inside a child class.

    Hi All,
    I've run into a snag developing a WPF multithreaded app where I need to call a method on the UI thread from my work thread, where the work thread is running a different class.
    Currently I am trying to use a delegate and an event in the 2nd class to call a method in the 1st class on the UI thread. This so far is not working as because the 2nd class is running in its own thread, it causes a runtime error when attempting to call
    the event.
    I've seen lots of solutions referring to using the dispatcher to solve this by invoking the code, however my work thread is running a different class than my UI thread, so it seems the dispatcher is not available?
    Below is as simplified an example as I can make of what I am trying to achieve. Currently the below code results in a "The calling thread cannot access this object because a different thread owns it." exception at runtime.
    The XAML side of this just produces a button connected to startThread2_Click() and a label which is then intended to be updated by the 2nd thread calling the updateLabelThreaded() function in the first thread when the button is clicked.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Threading;
    using System.Threading;
    namespace multithreadtest
    public delegate void runInParent();
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    threadUpdateLabel.Content = "Thread 1";
    private void startThread2_Click(object sender, RoutedEventArgs e)
    thread2Class _Thread2 = new thread2Class();
    _Thread2.runInParentEvent += new runInParent(updateLabelThreaded);
    Thread thread = new Thread(new ThreadStart(_Thread2.threadedTestFunction));
    thread.Start();
    public void updateLabelThreaded()
    threadUpdateLabel.Content = "Thread 2 called me!";
    public class thread2Class
    public event runInParent runInParentEvent;
    public void threadedTestFunction()
    if (runInParentEvent != null)
    runInParentEvent();
    I'm unfortunately not very experienced with c# so I may well be going the complete wrong way about what I'm trying to do. In the larger application I am writing, fundamentally I just need to be able to call a codeblock in the UI thread when I'm in a different
    class on another thread (I am updating many different items on the UI thread when the work thread has performed certain steps, so ideally I want to keep as much UI code as possible out of the work thread. The work threads logic is also rather complicated as
    I am working with both a webAPI and a MySQL server, so keeping it all in its own class would be ideal)
    If a more thorough explanation of what I am trying to achieve would help please let me know.
    Any help with either solving the above problem, or suggestions for alternative ways I could get the class in the UI thread to do something when prompted by the 2nd class in the 2nd thread would be appreciated.
    Thanks :)

    If I follow the explanation, I think you can use MVVM Light messenger.
    You can install it using NuGet.
    Search on mvvm light libraries only.
    You right click solution in solution explorer and choose manage nugget...
    So long as you're not accessing ui stuff on these other threads.
    using GalaSoft.MvvmLight.Messaging;
    namespace wpf_Tester
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    Messenger.Default.Register<String>(this, (action) => ReceiveString(action));
    private void ReceiveString(string msg)
    MessageBox.Show(msg);
    Dispatcher.BeginInvoke((Action)delegate()
    tb.Text = msg;
    private void Button_Click(object sender, RoutedEventArgs e)
    Task.Factory.StartNew(() => {
    Messenger.Default.Send<String>("Hello World");
    What the above does is start up a new thread - that startnew does that.
    It sends of message of type string which the main window has subscribed to....it gets that and puts up a message box.
    The message is sent from the window to the window in that but this will work across any classes in a solution.
    Note that the receive acts on whichever thread the message is sent from.
    I would usually be altering properties of a viewmodel with such code which have no thread affinity.
    If you're then going to directly access properties of ui elements then you need to use Dispatcher.BeginInvoke to get back to the UI thread.
    I do that with an anonymous action in that bit of code but you can call a method or whatever instead if your logic is more complicated or you need it to be re-usable.
    http://social.technet.microsoft.com/wiki/contents/articles/26070.aspx
    Hope that helps.
    Technet articles: Uneventful MVVM;
    All my Technet Articles

  • Calling WSAGetLastError() from an IOCP thread return incorrect result

    I have called WSARecv() which returned WSA_IO_PENDING. I have then sent an RST packet from the other end. The GetQueuedCompletionStatus() function which exists in another thread has returned FALSE as expected, but when I called WSAGetLastError() I got
    64 instead of WSAECONNRESET.
    So why WSAGetLastError() did not return WSAECONNRESET?

    Hi Tom_912,
    Thanks for posting in MSDN forum.
    Where do you call WSAGetLastError and get 64? From your description, It seems that you call WSAGetLastError after GetQueuedCompletionStatus() function.
    Read the document:
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa364986(v=vs.85).aspx
    We should call GetLastError to get extended error information instead of WSAGetLastError function. For the error code 64
    ERROR_NETNAME_DELETED, It means that the specified network name is no longer available.
    https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx it's likely that your connection has gone away since GetQueuedCompletionStatus return false.  Is that as your expect? If not, please provide more details about what
    you do, and it would be better if you could share us some code.
    Best regards,
    Shu Hu
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Can we call Swing Utitlies.Invoke Later from Swing worker

    Hi
    I know The worker thread is to run as a seperate thread for time consuming process.i.e non GUI stuff.
    But my question is Can we call invokeLater from SwingWorker
    Thanks
    Rahul

    codingMonkey wrote:
    rahulm_32003 wrote:
    Hi
    yes it is correct.But my question to know whether can we call InvokeLater from Swing worker.What happens if we do like that.Does it make any problem IN GUI
    ThanksTry it.Of course you can try to do that. But why do you want to? Why do you insist on doing something silly?
    Post an example SwingWorker where this makes sense to do.

  • System() from a multi-threaded app

    The man page for system(3S) states that its MT-Level is "unsafe." Nonetheless we need to call system() from a multi-threaded application. At present we "just go ahead and do it," and of course it doesn't work well. I'm not entirely sure of the details of the failure -- it's more a colleague's baby than mine -- but I believe the system() call often fails to complete ("hangs").
    Is there a thread-safe equivalent-or-replacement for system()? Surely the need to launch other applications from a multi-threaded application is commonplace today? How is it done safely-and-correctly?

    Hi,
    system() is not thread safe because it internally uses vfork() system call which in turn is not MT-safe . When you do a vfork()/fork1() in threaded applications only the thread which issues the call gets duplicated in the child process , which could result in dead lock problems . Solution of running system() under the protection of a lock may not help to avoid this problem.
    If you're using Solaris thread library , fork() + exec() is a safe substitute for system() . If you are using Posix library , use pthread_atfork() to make sure that you handle the locks properly before/after forking.
    Hope this helps.
    Thanks,
    Prajeesh

  • Threading- Can I call methods from specific threads or from all in a group?

    I've just recently started working with threads. I've done a lot of searching and reading but I haven't seen the specific questions I'm wondering answered. Of course, it's about communication.
    The amount of newly created threads that will exist is indefinite. Sometimes I'll have one, sometimes ten. So I'll just call them t1 - t9. When I create them, I add them to a ThreadGroup - tg.
    This project contains 2 class files, Main and ThreadClass. I'll post all of the code so you can see what I'm doing.
    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i < 10; i++) {
                ThreadGroup tg = new ThreadGroup("tg1");
                Thread t = new Thread(tg, new ThreadClass("t" + i));
                t.start();
    public class ThreadClass extends Thread {
        public ThreadClass(String name) {
            super(name);
        public void run() {
            System.out.println("New Thread - " + getName());
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.out.println("Exception: " + e);
        public void printText() {
            System.out.println("Printing text from " + getName());
    }So whenever a new thread is created, it prints "New Thread - [ThreadNameHere]". But I also have printText() in ThreadClass that has not been used yet and that is what I really want to accomplish. Is there a way to call printText() by the thread group (tg1 in this case) so it is executed across all threads that belong to the group? Is there a way to call printText() in a specific thread from my Main class, such as "t3"?
    Thank you for your help!
    Edited by: sdouble on Sep 9, 2008 10:10 AM - Fixed a typo

    Yes, usually you want to implement Runnable, not extend Thread. You're not adding new functionality to Threads or making some kind of more-specific version of them.
    You can get each thread in your ThreadGroup back out into an array by using one of the varients of Enumerate, but nothing stops you from just putting your objects (that implement Runnable) into an ArrayList or any collection of your own that you want to as you make them, and then later iterating over it and calling the method that you want.
    Something like this...
    public class MyThread implements Runnable {
       public void run() { ... }
       public void printStuff() { ... }
    public static void main(String[] args) {
       MyThread a = new MyThread();
       MyThread b = new MyThread();
       ArrayList threadList = new ArrayList();
       threadList.add(a);
       threadList.add(b);
       for(MyThread thread : threadLIst) {
          thread.printStuff();
    }

  • Help calling JNI function from a java thread

    I am using the following code to call a JNI fuction from a java thread:
    public class CMSMessageHandler extends MessageHandler{
    static{
    System.loadLibrary("jastb");
    public native int cmsReadIt(ByteBuffer buff);
    private ByteBuffer dirbuf = null;
    /** Creates a new instance of CMSMessageHandler */
    public CMSMessageHandler() {
    // allocate to max size datagram
    dirbuf = ByteBuffer.allocateDirect(65536);
    public void readMessages(){
    /*Thread worker = new Thread(){
    public void run(){*/
    int count;
    while (true){
    try{
    count = cmsReadIt(dirbuf);
    } catch (Exception e){
    e.printStackTrace();
    worker.start();*/
    public static void main(String[] args) {
    CMSMessageHandler handler = new CMSMessageHandler();
    handler.readMessages();
    When I run this main method with the thread commented out, it works great. When I run the main method with the thread, it works great for a while, and then funny things start happening with the native library I am using. My native library uses shared memory, signals, and semaphores. It feels a bit like my java program is stomping on the resources that my native library is using, when a run the java program with a thread.
    Is there something I don't know about calling native code from a thread? Should I be doing something explicitly to protect my native library's shared memory, signals, or semaphores?
    Thanks,
    Lisa.

    Does the library do any initialization when loaded? Does it make a dangerous assumption that the thead calling cmdReadIt will always be the same thread that initially loaded it? Try loading the library in the worker thread instead of in the main thread via the static initializer.Yes. There is a call to another native method cmsOpenIt that does CMS initialization. I put cmsOpenIt as well as the System.loadLibrary("jastb") in the worker thread and I'm still experiencing the same problems.
    Incidently, the mere presence of another Thread in this program does not seem to cause problems. It's only when I run calls to cmsReadIt in a thread that I get into trouble.
    For example, this works fine:
    public class CMSMessageHandler extends MessageHandler{
        public native int cmsReadIt(ByteBuffer buff);
        public ByteBuffer dirbuf = null;
        static {
            System.loadLibrary("jastb");
        public CMSMessageHandler() {
            // allocate to max size datagram
            dirbuf = ByteBuffer.allocateDirect(65536);
        public void readMessages(){
            try{
                int count = 0;
                while (true){
                    count = cmsReadIt(dirbuf);
            } catch (Exception e){
        public static void main(String[] args) {
            CMSMessageHandler handler = new CMSMessageHandler();
            Thread worker = new Thread(){
                public void run(){
                    while (true){
                        try{
                            Thread.currentThread().sleep(1000);
                            System.out.println("sleep thread.");
                        } catch (Exception e){
                            e.printStackTrace();
            worker.start();
            handler.readMessages();  
        }Are there JVM flags that I should experiment with that might help mitigate/diagnose this problem?

  • Correct clipping when calling "paint()" from thread

    How do I achieve correct clipping around JMenus or JTooltips when calling paint() for a Component from a background thread?
    The whole story:
    Trying to implement some blinking GUI symbols (visualizing alerts), I implemented a subclass of JPanel which is linked to a Swing timer and thus receives periodic calls to its "actionPerformed()" methods.
    In the "actionPerformed()" method, the symbol's state is toggled and and repainting the object should be triggered.
    Unfortunately, "repaint()" has huge overhead (part of the background would need to be repainted, too) and I decided to call "paint( getGraphics() )" instead of it.
    This works fine as long as there is nothing (like a JMenu, a JComboBox or a JTooltip) hiding the symbol (partially or completely). In such case the call to paint() simply "overpaints" the object.
    I suppose setting a clipping region would help, but where from can I get it?
    Any help welcome! (I alread spent hours in search of a solution, but I still have no idea...)

    For all those interested in the topic:
    It seems as if there is no reliable way to do proper clipping when calling
    "paint()".
    The problem was that when my sub-component called "repaint()" for itself, the underlying component's "paintComponent()" method was called as well. Painting of that component was complex and avoiding complexity by restricting
    on the clipping region is not easily possible.
    I have several sub-components to be repainted regularly, resulting in lots of calls to my parent component's "paintComponent()" method. This makes the
    repainting of the sub-components awfully slow; the user can see each one begin painted!
    Finally I decided I had to speed up the update of the parent component. I found two possible solutions:
    a) Store the background of each of the sub-components in a BufferedImage:
    When "paintComponent()" is called: test, if the clipping rectangle solely
    contains the region of a sub-component. If this is true check if there
    is a "cached" BufferedImage for this region. If not, create one, filling
    it with the "real" "paintComponent()" method using the Graphic object of
    the BufferedImage. Once we have such a cached image, simply copy it the
    the screen (i.e. the Graphics object passed as method parameter).
    b) To avoid the handling of several of such "cached" image tiles, simply
    store the whole parent component's visible part ("computeVisibleRect()")
    in a BufferedImage. Take care to re-allocate/re-paint this image each
    time the visible part changes. (I need to restrict the image buffer to
    the visible part since I use a zooming feature: Storing the whole image
    would easily eat up all RAM!) In the "paintComponent()", simple check
    if the currently buffered image is still valid - repaint if not -
    and copy the requested part of it (clip rect) to the screen. That's it!
    The whole procedure works fine.
    Best regards,
    Armin

  • Why copy option from recent call numbers is not working on ios7 [recent call logs in phone]?

    why copy option from recent call numbers is not working on ios7 [recent call logs in phone]?

    Here is a copy of my expressions and a copy of my data. The expressions match up going from left to right
    Code.CalcPTD2(Lookupset(FORMAT(Fields!REALDATE.Value,"Long Date"),FORMAT(Fields!CallbackDate.Value,"Long Date"),Fields!DailyHours.Value,"DataSet4"))
    sum(Code.CalcPTD2(Lookupset(FORMAT(Fields!REALDATE.Value,"Long Date"),FORMAT(Fields!CallbackDate.Value,"Long Date"),Fields!DailyHours.Value,"DataSet4")))
    count(Code.CalcPTD2(Lookupset(FORMAT(Fields!REALDATE.Value,"Long Date"),FORMAT(Fields!CallbackDate.Value,"Long Date"),Fields!DailyHours.Value,"DataSet4")))
    PUBLIC SHARED FUNCTION CalcPTD2(LookupArray AS OBJECT) AS INTEGER
         DIM i,Total AS INTEGER
         Total = 0
         FOR i = 0 to UBOUND(LookupArray)
               Total = Total + CINT(LookupArray(i))
         NEXT i
     NumberTimes  =   NumberTimes +1
    RETURN  Total
    END FUNCTION

  • Call EJB from a thread , pb with lookup

    Hello,
    I have seen taht it is possible to call an EJB within a thread that can act as a client. But in my case when the thread calls the EJB method the lookup failed. I do exactly the same like if I call the ejb from an external client.
    In my case I have got the following architecture:
    one MDB which receive a message the pass the a "manager of thread" which select a thread and then this thread calls a session bean. Everything goes well until the thread call the EJB method and at this time the lookup fail. I call from local interface as I constructed my jar with all this components inside, i.e the MDB, the thread manager, threads and the session bean.
    I tried to call the session bean from the MDB in the same way I have done from the thread and in that configuration its ok.
    Is there a specific manner to lookup an ejb when we want to call it from a thread or simply this configuration is completely impossible?
    Thanks for any advice

    insert the following code before creating the InitialContext:
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

  • TS1630 My Iphone 4s reciever is not working properly, when i call someone from my iphone 4s.  can any one help me how to solve this problem?

    My Iphone 4s reciever is not working properly, when i call someone from my iphone 4s.  can any one help me how to solve this problem?

    You might like to define "not working properly".

  • Security Sandbox Violation when calling a remote service from a worker

    From my application, I make calls to a BlazeDS server, that works fine.
    I added a worker that calls the same services on the same server. But then, only for the calls from the worker, I have a Security Sandbox Violation error. I launch the application from FB in debug mode.
    This is the message :
    Error: [strict] Ignoring policy file at http://xxxxxxxxxxxx/crossdomain.xml due to incorrect syntax.  See http://www.adobe.com/go/strict_policy_files to fix this problem.
    *** Security Sandbox Violation ***
    Connection to http://xxxxxxxxxxxxxx/appstore-admin/messagebroker/amfpolling halted - not permitted from file:///D:/Projects/appstoreClientsNext/MultiAppstoreAdmin/bin-debug/MultiAppstoreAdmin.swf
    Error: Request for resource at http://xxxxxxxxxxxxx/appstore-admin/messagebroker/amfpolling by requestor from file:///D:/Projects/appstoreClientsNext/MultiAppstoreAdmin/bin-debug/MultiAppstoreAdmin.swf is denied due to lack of policy file permissions.
    What should I do to allow the worker to make remote calls ?

    I made some progress on this. There are two different cases :
    1) The service you want to access has a crossdomain.xml file
    All the workers can access the service without a problem.
    2) The service you want to access doesn't have a crossdomain.xml file
    Whether you launch from FB in debug mode or you put your application on the same server you are trying to access, only the primordial worker will access the service, the other workers will encounter a security error.
    I believe this is a bug. Shouldn't a worker have the same access privileges as the primordial worker ?

  • We have a 5s active on our account.  After turning on a previously active 4s (it had the same number)  The 5s can no longer place call and when you call it from another phone the 4s rings, but will not pick up.  Texting over the cell networks works fine.

    We have a 5s active on our account.  After turning on a previously active 4s (it had the same number)  The 5s can no longer place call and when you call it from another phone the 4s rings, but will not pick up.  Texting over the cell networks works fine.  Any suggestions??

    hens0861,
    Hmm, let's ensure this is working as it should be! So what phone should be active on your account? Did you switch the devices online or how to did you activate the 5s? Please share details.
    KarenC_VZW
    Follow us on Twitter @VZWSupport

  • Can i get help on how I can successfully install the new google voice video chat software. I keep having an install error. My google voice phone always worked until a week ago when suddenly google would not let me call out from any browser

    Can i get help on how I can successfully install the new google voice video chat software. I keep having an install error. My google voice phone always worked until a week ago when suddenly google would not let me call out from any browser until I installed their new google voice and video chat (made by vidyo) software. I was told by genius bar to install Yosemite, which I did. But that did not solve the problem. I removed macKeeper, as well, since a techie friend told me that could be the cause. Nothing so far has worked.  When the problem first happened, it seemed to only happen in Chrome. Google voice calling out worked fine in safari, for about a day or so. Now I cannot call out from any browser. I can, however receive calls, and make calls within the video hangout.
    I can be contacted directly if questions at gary at couplewise dot followed by the usual extensin

    You can only suspend service for 3 months at a time (with or without payment) and only twice a year.

  • Calling NI objects from aa Afx thread

    Hi,
    I have a Dialog class in Visual c++ 2003 "TESTDlg.h and TestDlg.cpp"
    In TestDlg.h i have publikc members:
    public:
       CNiButton m_nbool1;
        CNiButton m_nbool2;
        CNiButton m_nbool3;
        CNiButton m_nbool4;
        CNiButton m_nbool5;
    in TestDlg.cpp i have a worker thread: CWinThread* pThread = AfxBeginThread( MyFunc_, this, THREAD_PRIORITY_NORMAL, 0, 0,NULL);
    MyFunc function gets the "this" pointer and obtains a reference to the Dialog.
    I can access all the Public members within TestDlg but the NIButtons(although they are also public)
    My code returns with error:
    Unhandled exception at 0x7c812a5b in TestDlg.exe: Microsoft C++ exception: NI::CNiOleException @ 0x01bafb54.
    How can i fix that?

    I realise that this is some time ago, but I'm working on a similar project and need some MFC assistance.
    I've created a DLL with MFC, but I need to use Multithreading to collect some data.
    Since all the calls look similar to
    _declspec(dllexport) HRESULT __cdecl OpenPort ( unsigned char DeviceID )
     return ( m_pBrickInput->OpenDevice ( DeviceID ) );
    I haven't had any reason to create any instances of the class.
    Now, when I try to do this...
    static void StartRead(void)
     CBrickApp *MyApp;
      MyApp = new (CBrickApp);
      MyApp->StartReader();
    void CBrickApp:tartReader(void)
    CWinThread  *pReaderThread;
    //  this->Data.SetSize(0);
      pReaderThread = AfxBeginThread (ReadThread, (void *)this, THREAD_PRIORITY_HIGHEST,
              0, 0, NULL );
    the MFC Linker complains...
    Any suggestions ?
    DOK 

Maybe you are looking for

  • Request to Make Withholding Tax info changeable on Cleared Line items

    Hello all, I got a new requirement where the client wants to change the withholding tax information in vendor cleared items. some documents got posted with wrong WT T type, now they want to make the changes to submit 1099 report. Withholding tax info

  • Looking for function module to update User data

    Hi All, I'm looking for function module/base table to update data into User (User-Specific Data) data. You can notice it under PRTE t.code. Thank you. Regards Kishore

  • Building a adf rich client component dynamically...

    Is it possible to specify the af:selectItem(s) in a af:selctOneChoice using af|forEach where the "items" attribute" calls a client side List or Array? Where can I find for documentation regarding EL expressions and how to call a client side varible i

  • ABAP Object (Up cast, Down Cast)

    Someone should let me know. Version 4.70 Enterprise was as follows. " Up Cast (Narrowing-Cast)   superclass = subclass. " Down Cast (Widening-Cast)   subclass ?= superclass. It is why the help of F1 is changed as follows from the version ECC 6.0. (Wi

  • Transformation & DTP deactivated in source system

    Hi, I am trying to load the data from one BI System to another BI system. I am generating Export Data Source for that . But the Issue is that when i am doing this, in  the source system transformation & DTP got Deactivated. Can any body tell why this