Having 2 objects running in separate threads

I am accessing cobol programs using the microfocus runtime for java. The problem with it is that a you can only run one instance of a cobol program at the same time, unless they are in separate threads.
Example:
CobolTextSearch cobol1 = new CobolTextSearch();
CobolTextSearch cobol2 = new CobolTextSearch();
cobol1.execute("FAMILY");
cobol2.execute("HISTORY");
System.out.println(cobol1.getRecord());
System.out.println(cobol2.getRecord());The output of this program results in HISTORY for cobol1 and HISTORY for cobol2. Where as if they were run in separate threads, I would have got FAMILY for cobol1.
So my question is, is there any way I can run these two objects in separate threads so that any time I access the object it will be in its own thread? I cant just run them in separate threads on the execute because each getRecord is interfacing with cobol. After execute I want to be able to read values from the cobol files to see if they match without having to read each record into memory on the java side.

No you are not missing anything, you just create a new thread each time you run something or you have to make a setter method to accept parameters for the next run and then a seperate method to actually make your routine execute.
public void setTask(String s){
  task2Execute = s; //task2Execute is global to the methods
public boolean runTask(){
  CobolTextSearch cobol = new CobolTextSearch();
  cobol1.execute(task2Execute);
//  other logic
}Here is what the docs say about threads: A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Similar Messages

  • Export from Crystal Reports 2008 viewer fails if run on separate thread

    I have a windows desktop application written in Visual Basic using Visual Studio 2008.  I have installed and am trying Crystal Reports 2008 to run a report.  Everything seems to work well except that when I preview a report (using the viewer control) and click the export button found in the upper left corner of that control, I get the following message:
    Error 5: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made.  Ensure that your Main function has STAThreadAttribute marked on it.  This exception is only raised if a debugger is attached to the process.
    I am a little confused on what to do exactly.  Is the problem because I am running in the Visual Studio 2008 IDE?  It says this exception is only raise if a debugger is attached to the process.  No, I tried running it outside the IDE.  The exception wasn't generated but the application hung when the button was clicked.
    It says the current thread must be set to single thread apartment (STA) mode.  If the report is run on its own thread, is the "current" thread the thread the report is running on or is the main application's UI thread?  I don't think I want to set my main application to single thread apartment mode because it is a multi-threaded application (although I really don't know for sure because I am new to multi-threaded programming). 
    My objective is to allow reports to run asynchronously so that the user can do other things while it is being generated.  Here is the code I use to do this:
        ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim backgroundProcess As System.ComponentModel.BackgroundWorker
            ' Start a new thread to run this report.
            backgroundProcess = New System.ComponentModel.BackgroundWorker
            Using (backgroundProcess)
                ' Wire the function we want to run to the 'do work' event.
                AddHandler backgroundProcess.DoWork, AddressOf PreviewReportAsynch_Start
                ' Kick off the report asynchronously and return control to the calling process
                backgroundProcess.RunWorkerAsync(sourceDatabase)
            End Using
        End Sub
        Private Sub PreviewReportAsynch_Start(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
            ' The source database needed to call preview report was passed as the only argument
            Call PreviewReport(CType(e.Argument, clsMainApplicationDatabase))
        End Sub
        ' Previews the report.  From the preview window, the user can print it.
        Public Function PreviewReport(ByVal sourceDatabase As clsMainApplicationDatabase) As FunctionEndedResult
            Dim errorBoxTitle As String
            Dim frmPreview As frmReportPreview
            ' Setup error handling
            errorBoxTitle = "Preview " & Name & " Report"
            PreviewReport = FunctionEndedResult.FAILURE
            On Error GoTo PreviewError
            ' Set up the crxReport object
            If InitializeReportProcess(sourceDatabase) <> FunctionEndedResult.SUCCESS Then
                GoTo PreviewExit
            End If
            ' Use the preview form to preview the report
            frmPreview = New frmReportPreview
            frmPreview.Report = crxReport
            frmPreview.ShowDialog()
            ' Save any settings that should persist from one run to the next
            Call SavePersistentSettings()
            ' If we got this far everything is OK.
            PreviewReport = FunctionEndedResult.SUCCESS
    PreviewExit:
            ' Do any cleanup work
            Call CleanupReportProcess(sourceDatabase)
            Exit Function
    PreviewError:
            ' Report error then exit gracefully
            ErrorBox(errorBoxTitle)
            Resume PreviewExit
        End Function
    The variable crxReport is of type ReportDocument and the windows form called 'frmPreview' has only 1 control, the crystal reports viewer. 
    The print button on the viewer works fine.  Just the export button is failing.  Any ideas?

    Hi Trevor.
    Thank you for the reply.  The report document is create on the main UI thread of my application.  The preview form is created and destroyed on the separate thread.  For reasons I won't get into, restructuring the code to move all the initialization stuff inside the preview form is not an option (OK, if you a really curious, I don't always preview a report, sometimes I print and/or export it directly which means the preview form isn't used).
    What I learned through some other research is that there are some things (like COM calls and evidently some OLE automation stuff) that cannot be run on a thread that uses the MTA threading model.   The export button probably uses some of this technology, thus the message stating that an STA threading model is required.  I restructured the code as follows to accomodate this requirement.  Here is a sample:
    ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim staThread As System.Threading.Thread
            ' Start the preview report function on a new thread
            staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep1)
            staThread.SetApartmentState(System.Threading.ApartmentState.MTA)
            staThread.Start(sourceDatabase)
        End Sub
        Private Sub PreviewReportAsynchStep1(ByVal sourceDatabase As Object)
            Dim staThread As System.Threading.Thread
            ' Initialize report preview.  This includes staging any data and configuring the
            ' crystal report document object for use by the crystal report viewer control.
            If InitializeReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase)) = FunctionEndedResult.SUCCESS Then
                ' Show the report to the user.  This must be done on an STA thread so we will
                ' start another of that type.  See description of PreviewReportAsynchStep2()
                staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep2)
                staThread.SetApartmentState(System.Threading.ApartmentState.STA)
                staThread.Start(mcrxReport)
                ' Wait for step 2 to finish.  This blocks the current thread, but this thread
                ' isn't the main UI thread and this thread has no UI anymore (the progress
                ' form was closed) so it won't matter that is it blocked.
                staThread.Join()
                ' Save any settings that should persist from one successful run to the next
                Call SavePersistentSettings()
            End If
            ' Release the crystal report
            Call CleanupReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase))
        End Sub
        ' The preview form must be launched on a thread that use the single-threaded apartment (STA) model.
        ' Threads use the multi-threaded apartment (MTA) model by default.  This is necessary to make the
        ' export and print buttons on the preview form work.  They do not work when running on a
        ' thread using MTA.
        Public Sub PreviewReportAsynchStep2(ByVal crxInitializedReport As Object)
            Dim frmPreview As frmReportPreview
            ' Use the preview form to preview the report.  The preview form contains the crystal reports viewer control.
            frmPreview = New frmReportPreview
            frmPreview.Report = DirectCast(crxInitializedReport, ReportDocument)
            frmPreview.ShowDialog()
        End Sub
    Thanks for your help!
    Andy

  • Will subsequent calls to an object running in a thread run in the thread?

    Hi,
    If I start a thread with an empty run method and then make a call to the object that I started in the thread, will the method call run in the other thread? For example:
    class ThreadClass implements Runnable {
        public void someMethod() {
        public void run() {
    class ThreadCaller {
        private ThreadClass threadClass;
        public ThreadCaller() {
            threadClass = new ThreadClass();
            Thread thread = new Thread(threadClass);
            thread.start();
        public blah() {
            threadClass.someMethod();
    }Will the method call in blah() run in the same thread as ThreadCaller, or will it run in the thread that was started in ThreadCaller's constructor?
    Thanks,
    Dan

    Djaunl wrote:
    vanilla_lorax wrote:
    Djaunl wrote:
    Is there a way to keep the thread alive until the object that started the thread is terminated,Objects don't get terminated. What do you mean?I want the thread to stay alive indefinitely until I arbitrarily terminate it makes more sense. The thread will stay alive until its run method completes. The canonical approaches are
    public void run() {
      while (!Thread.interrupted()) { // NOT isInterrupted()
        // do stuff
        // if you need to catch InterruptedException, do this:
        try {
        catch (InterruptedException exc) {
          Thread.currentThread().interrupt();
    }And then from another thread, call theAboveThread.interrupt() when it's time to stop. Read the docs in interrupt(), interrupted(), the interrupt flag, etc.
    OR
    while (!done()) {
      // do stuff
    }and then another thread calls setDone(true) or somesuch when it's time to stop. Note that all access to done--both get and set--must be synchronized, or done must be declared volatile. Also note that you may still have to handle interrupts, so you may have some repeated code with this approach--testing both done() and interrupted().
    Let me give the end-goal of this.
    Currently, I have a "main" thread which the user can input commands into, and another thread which occasionally runs in the background. When I want something to run in the background, I just create a new thread. However, I figured it'd be more efficient to have one thread running in the background to do something as opposed to spawning hundreds of new threads to do the same task over and over. If the task happens VERY frequently and what it does is VERY small and quick, then the overhead of thread creation may make this a valid approach. Otherwise, don't overcomplicate it. Since you're new to threads, first get it working where you spawn one thread for each background task. Then move on to thread pooling. Look into ThreadPoolExecutor and related classes.
    http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html

  • Running in separate thread??

    Hi
    I have a code which generates a pdf file. What i wan is for it to run in a separate thread. The filling and creation of the pdf file should be running while i am doing other stuffs.. just like in downloading. the user can browse or do other things in the mean time while waiting.. when the pdf file is ready to be viewed, then the program should interupt whatever the user is doing and pop up a pdf viewer to display the file.
    Is there any way to call the pdf viewer in my code? And how should i do the interrupt? Plus, how do i specify that the pdf creation should run in a separate thread?
    thanks in advance.
    tbozu

    alright, handling the interrupt is highly dependant on the rest of your application, so I won't touch that one, but.
    To create your file in a different thread, wrap the method in it's own thread, so it would look similar to
    new Thread() {
    public void run() {
    writeMyFile(); // your method here
    }.start();then, to start the pdf viewer, try using the Runtime.exec() utilities.
    good luck to you!

  • How to stop Native Meto running in separate thread?

    I have a long working NM and run it in separate thread using SwingWorker class. If I want to stop that metod, i use interrupt(), but it seems to be a wrong way. It looks like NM go on working, and when I call other NM it throws an Access Violation Exception.
    Is there any ideas?
    Thank you. Charis.

    The interrupt() method does not stop the thread. It sets a flag. Are you checking that flag in your native code?

  • Using XMLParser as a single object used by different threads

    Hi,
    I'm trying to use the XMLParser object as a parser used by
    several different objects, probably running under separate
    threads.
    Each such object will implement its own callback, the idea being
    that the callback supplied to the parser upon initialization,
    will actually call the callback implemented by the object that
    called parse. I thought about doing this by using the "context"
    passed to the XMLParser, if I could change it after
    initialization and before each call to XMLParser.parse that I
    would be able to switch between calling objects, and thus allow
    multiple threads to use the same parser.
    The problem here is that the SAX callback implementation
    functions are defined "extern C" and I can't get them in the
    context of an object.
    Is there any way at all to accomplish this?
    Thanks
    J Galore

    Hi,
    You can use "select for update" to lock this row but locking means other sessions will hang and wait until lock is released. If this is ok for you, go for it.
    Other option is to use a flag column which you should set to "1" so that other threads don't use the row with flag vlaue "1"
    Salman

  • Timer in separate Thread.

    Hi.
    In my application i have a timer use to tick after every second and update a lable on UI. problem i was facing was that when time is enable none of the touch event was working.
    I googled it and found that i have to call timer function from another thread..
    after some effort i manage to run a separate thread. but now i m facing problems in calling a timer function here is the code.
    Create Thread
    myThread = [[NSThread alloc] initWithTarget:self selector:@selector(SapThread:) object:nil];
    [myThread start];
    SapThread Function....
    - (void)SapThread:(id)info {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSTimer *appTimer = [NSTimer scheduledTimerWithTimeInterval:(1/20) target:self selector:@selector(UpdateTime) userInfo:nil repeats:YES];
    [pool release];
    UpdateTime Function for timer
    -(void) UpdateTime
    //set lable value.
    problem is this that UpdateTime function never called.
    Thankz in advance
    Muhammad Usman Aleem

    As I tried to explain above, I didn't expect your code to work after you corrected the firing method signature.
    Your detached thread doesn't run until you release your myThread object. It terminates when execution reaches the end of your SapThread method. That's why the timer never fires when you run it in that thread.
    In any case, I think sptrakesh is absolutely correct. There's no reason a timer in the main thread should prevent you from catching touch events. So I think you have two major points of confusion:
    1) Your thread isn't doing anything, since it terminates before the timer ever fires once;
    2) You have mis-diagnosed the problem with the touch events and don't need a new thread. I.e. even if you got a detached thread working to fire your timer, that's not going to solve your touch problem.
    I think bringing a new thread into the mix has gotten you in over your head and taken your attention away from the primary problem. So take sptrakesh's advice. Put the timer back into the main thread and focus on why you're not catching the events you want.

  • Trouble with TestStand running VB DLLs compiles in separate threads

    I have an application that uses DLLs written in VB 6 to manipulate hardware. The hardware is Stepper Motors controlled via the NI CAN bus card, and two instruments controlled via the GPIB PCI card. I have written the two DLLs to use the same NI PCI GPIB and the same NI CAN BUS card. (One instrument per DLL and One Motor per DLL)
    Test stand is then creating the DLLs and running them in separate threads. I have the one DLL Call in a subsequence running as a separate thread, and the other DLL is in the main sequence. I have a GOTO step with preconditions set so that the main sequence only continues after the separate thread in the subsequence is finished.
    The problem I am having is that these D
    LLs work OK when I run them both in the VB debugger. The program even works when I run the main thread in the debugger, and the subsequence is run compiled.
    The problem is, that if I try to run both of these DLLs compiled It seems as if the subsequence DLL never executes.

    To Tuxamation -
    Nothing comes to mind as to why this would happen. VB 6 automation DLLs are used all the time for code modules.
    Note that when MSVB debugs a DLL, it is actually running the DLL as an EXE server within the MSVB process and not in TestStand's process that is using it. I typically found that there is typically a subtle difference in behavior between running the server as an EXE or DLL server.
    A simple way to determine if the TestStand call is reaching your DLL is to place a MsgBox function call in the DLL entry point and immediately return, ie. bybassing your existing code.
    So, if the call is being made to your DLL, you could then enable the Visual Basic project option on the Compile tab, "Create Symbol Debug Info" and recreate your VB DLL.
    You can then attach Microsoft Visual Studio (C++ debugger) to the TestStand process, open the file that contains the entry point in to DLL that TestStand calls, set a breakpoint, and see if the breakpoint is reached.
    Scott Richardson
    Scott Richardson
    National Instruments

  • How can I debug a sequence that has a subsequence is running in a separate thread?

    Hi,
    How can I debug a sequence that has a subsequence is running in a separate thread?
    I have to have a continues check for a  digital in signal to be able to terminate the sequence if a physical button is pushed.
    This is running in a separate thread, but this way I cannot debug the main sequence.
    Is there any workaround for this?
    Thanks,
    Andras

    This KB might help you:
    http://digital.ni.com/public.nsf/websearch/46D1E157756C37E686256CED0075E156?OpenDocument
    Let me know if this does not help.
    Allen P.
    NI

  • Running SSRS report locally in separate thread

    We're using ASP.net with .Net 4, developing with Visual Studio 2012.  We use SSRS 2012sp1 with local reports, so exporting the report ourselves instead of using a reportviewer control (and not using the SQL Reporting service).  The reports are executing
    fine when we export the report in the main thread, but if we spawn a worker thread and run a report there we receive the following error when calling Render():
    Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Failed to load expression host assembly. Details: Invalid token
    for impersonation - it cannot be duplicated.
    We only receive this when running a report that uses expressions on a separate thread.  I've tried running the application pool under all the default built-in accounts (NetworkService, etc), and under admin user accounts to no avail.
    This didn't occur with the previous version of our application which used .net 3.5.  From what I've read, its because of a new security model in .net 4.
    I've tried running the application pool under LocalSystem, that does not help.
    We are not loading any custom DLLs in the report.  I think its trying to load the expression DLL that SSRS compiles from expressions on the report.  We don't have any outside DLLs on the report, only basic report expressions.  This works fine
    in-process, it only fails when we try to run it on a separate thread.
    Microsoft.Reporting.WebForms.LocalProcessingException: An error occurred during local report processing. ---> Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Failed to load expression host assembly. Details: Invalid token for impersonation - it cannot be duplicated.
    at Microsoft.ReportingServices.RdlExpressions.ReportRuntime.ProcessLoadingExprHostException(ObjectType assemblyHolderObjectType, Exception e, ProcessingErrorCode errorCode)
    at Microsoft.ReportingServices.RdlExpressions.ReportRuntime.LoadCompiledCode(IExpressionHostAssemblyHolder expressionHostAssemblyHolder, Boolean includeParameters, Boolean parametersOnly, ObjectModelImpl reportObjectModel, ReportRuntimeSetup runtimeSetup)
    at Microsoft.ReportingServices.OnDemandProcessing.Merge.Init(Boolean includeParameters, Boolean parametersOnly)
    at Microsoft.ReportingServices.OnDemandProcessing.Merge.Init(ParameterInfoCollection parameters)
    at Microsoft.ReportingServices.ReportProcessing.Execution.ProcessReportOdp.CreateReportInstance(OnDemandProcessingContext odpContext, OnDemandMetadata odpMetadata, ReportSnapshot reportSnapshot, Merge& odpMerge)
    at Microsoft.ReportingServices.ReportProcessing.Execution.ProcessReportOdp.Execute(OnDemandProcessingContext& odpContext)
    at Microsoft.ReportingServices.ReportProcessing.Execution.RenderReportOdpInitial.ProcessReport(ProcessingErrorContext errorContext, ExecutionLogContext executionLogContext, UserProfileState& userProfileState)
    at Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension newRenderer)
    at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.RenderReport(IRenderingExtension newRenderer, DateTime executionTimeStamp, ProcessingContext pc, RenderingContext rc, IChunkFactory yukonCompiledDefinition)
    at Microsoft.Reporting.LocalService.CreateSnapshotAndRender(ReportProcessing repProc, IRenderingExtension renderer, ProcessingContext pc, RenderingContext rc, SubreportCallbackHandler subreportHandler, ParameterInfoCollection parameters, DatasourceCredentialsCollection credentials)
    at Microsoft.Reporting.LocalService.Render(String format, String deviceInfo, String paginationMode, Boolean allowInternalRenderers, IEnumerable dataSources, CreateAndRegisterStream createStreamCallback)
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings)
    --- End of inner exception stack trace ---
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.LocalReport.Render(String format, String deviceInfo, PageCountMode pageCountMode, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.Report.Render(String format, String deviceInfo, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at IxSS.Infolinx.Report.MicrosoftInfolinxReport.ExportReport(String strFileFullyQualifiedPath, String strExportType, String strFilterDesc, Dictionary`2 extraParams, String area)
    at IxSS.Infolinx.Report.MicrosoftInfolinxReport.ExportReport(String strFileFullyQualifiedPath, String strExportType, String strFilterDesc, Dictionary`2 extraParams)

    Was that a joke?
    If not, no, there is no duplicated token to run the report.  I'm guessing it means some sort of security token, but if its something to do with the user running the application pool, changing that user has no effect.  I've enabled and disabled
    asp.net impersonation to no effect as well.

  • Problem is having more than one FrameAccess object running in multithreads

    Hi all,
    I have a problem with my system which uses JMF for frame capture for frame processing. The system flow is like this -
    I use a FrameAccess.java (modified from the one provided by Sun) to grab frames. I use 5 different threads to create an associated FrameAccess object (i.e. one thread owns its own FrameAccess object ). And then they will do their own processing (all of them are implementing motion estimation thing using buffered image from the frame).
    The problem is , when I examine the frames captured from the 5 threads, something irregular happened.
    For example, the thread A (capturing video A) may return frames captured from video C. such scenairo happened without signs and patterns. Sometimes a thread even return something like half frame from video C and half from video B.
    I would like to know if there is any way to check if it is the problem of JMF (can't synchronize frame capturing), or it's the problem of FrameAccess object (but they are in five independent threads ><")
    Thank you very much...

    It is a problem with how you are handling threads.
    Thread one calls frame access, then thread 2 calls frame access, and it is possible that thread one will only get half a frame.
    You will probably have success by syncronizing your calls to frameaccess(lock), and then unlock when that thread has a complete frame.
    This way only one thread will access frame access, at any one time.
    I have had this exact problem, when trying to capture every single frame, save it to jpeg.
    Half the problem was writing to disk before the frame was complete, thus showing have a picture.

  • Can CheckInRequest.Item object be used between threads?

    I have inherited a custom connector and am helping figure out a problem that occurred when my predecessor attempted to improve performance uploading assets by releagating the insertion into the DAM into a separate thread.  He did this in the CheckInHandler class by handing the object of type CheckinRequest.Item returned in the list returned by getItemList(request) to a separate thread run by a thread request pool.
    However when this thread attempts to perform the upload, the input stream returned by item.getContent() appears to have been truncated.  This means in practice that a zero byte file gets uploaded.  The problem goes away if I replace the code that sends the item to another thread to run synchronously in the CheckInHandler.
    First question is what is going on?  The second question is are there any suggested best practices to optimizing perofrmance of insertions.  This code was added in response to compaints that the Adobe applications (such as Illustrator) froze for a prolonged period when uploading assets to the DAM.
    Thanks for any help.
    Cheers,
    Lyman

    > download the role, manipulate the download file so that it contains the data for all derived roles
    I do agree (and use it myself as well, allbeit with Excel VBA routines) but this advise should be accompanied by the warning that :the checks in PFCG uploads are insufficient and minor flaws in your file can create an awfull mess. Practice a lot, and do this on sandbox clients/systems. Basically the fixed record length of table entries within the download files is something to very carefully watch. Having proper knowledge of the tables and data structure for roles is a must in my opinion.
    If you search the forums for mass creation of (derived) roles with ECATT you'll find safer options as well. It may leave some manual work but that automatically includes all PFCG's checks and safeties.
    Uploads skip more checks than I find comfortable......

  • Cannot Open Form Created on Separate Thread After Closing

    My application communicates with a device that has several sensors.  As the sensors collect data, they send messages over the com port.  I have written a class to communicate with the device.  As the messages come in and are processed, the
    class raises events that the application responds to.
    The main window of the application handles the communication with the device and displays several statistics based on the data collected.  When the user presses a button on the device, a specific event is raised.  The main window create a separate
    thread and opens a child window.  When the child window is open, the user opens a valve to dispense the product.  As the product is dispensed, a flow meter connected to the device measures the volume of product dispensed.  The flow meter generates
    messages to indicate the volume dispensed.  I need to be able to send messages from the main window to the child window so that the child window displays the volume.  When the user is done, they close the valve dispensing the product and press the
    "End" button on the child window.  The child window then updates several variables on the main window, makes a couple of database calls to record how much product was dispensed and by whom and then closes.
    I need to run the child window using a separate thread as both windows need to be able to process commands.  If only one window has control the program doesn't work at all.  I have it figured out so that everything is working.  I can open
    the child window, dispense product, se the amount of product dispensed in the child window (the main window processes commands from the device and updates the label on the child window using a delegate), closes the window (using Me.Close()) and updates the
    main display with the updated data.  The problem is that when a user goes to dispense product a second time, I get the following error:
      A first chance exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll
      Additional information: Cannot access a disposed object.
    I thought that maybe I could hide the window (change Me.Close() to Me.Hide) and then just show it.  When I do that I get this error:
      A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
      Additional information: Cross-thread operation not valid: Control 'frmPour' accessed from a thread other than the thread it was created on.
    Both of these errors make sense to me, I just can't figure out how to make it work.
    First I have to declare the child window as a global variable as I need to access the window from a couple of the event handlers in the main form.
    Public frmMeasure As New frmPour
    When the user presses the button on the device to dispense the product, the event handler executes this code to open the child window.
    Private Sub StartPour(sAuthName As String, sAuthToken As String, iStatus As Integer) Handles Device.Pour
    Dim th As System.Threading.Thread = New Threading.Thread(AddressOf Me.OpenDispenseWindow)
    th.SetApartmentState(ApartmentState.STA)
    th.Start()
    End If
    End Sub
    Which executes this code:
    Public Sub OpenDispenseWindow()
    frmMeasure.sNameProperty = sCurrentUserName
    frmMeasure.sAuthTokenIDProperty = sUserToken
    Application.Run(frmMeasure)
    bAuthenticated = False
    bPouring = False
    dSessionVolume += GetTapConversion(sCurrentValve) * iFinalTick
    UpdateDisplayDelegate(iValveID)
    End Sub
    It doesn't matter if I use Me.Close() or Me.Hide(), both methods fail on the Application.Run(frmMeasure) line with the errors shown above. 
    For the Me.Close() method, my thinking is that the global frmMeasure object is getting disposed when I close the child window.  Is there any way that I can re-instantiate it when I go to display the window again?
    For the Me.Hide method, is there any way that I can track the thread that created it in the main window and when I go to call it a second time, detect that it is already available and just Show() it?
    Any hints, tips or suggestions are appreciated.
    Thanks.
    John
    John

    To be honest, I have only grasped < 100% of your message in detail, but...: Windows that have a parent<->child relation must be running in the same thread. In addition, after closing a modeless window, you must not use it anymore. Instead, create
    a new instance.
    What happens if you do not create a new thread but instead open the child in the same thread (which is obligatory)? You wrote it doesn't work, but I don't know why?
    "First I have to declare the child window as a global variable".
    How do you define "global"? Normally this is a variable in a Module declared with the scope Public or Friend. But I guess you mean a field of the Form (a variable at class level in the Form).
    "I need to be able to send messages from the main window to the child window so that the child window displays the volume."
    Why does the main window has to send the messages? Can't the child window handle the device's messages itself?
    "I need to run the child window using a separate thread as both windows need to be able to process commands."
    Process commands from the device, or commands from the user operating the Forms?
    Armin

  • Is the main program seen as a separate thread ?

    I wanted to stop a GUI based program opening too fast because the splash screen wasn't seen for long enough.
    So I tried to use the Thread and Runnable classes within the GUI constructor.
    By trying different things, I got it to do as I wanted : a delay of 10 seconds before showing the program's GUI.
    But I don't understand why main is not seen as a separate thread and thus continue to make itself visible no matter what the delayThread status may be.
    // Constructor:
    public Hotel (int numberIn)
             // Create the time delay thread so that users may enjoy the splash !
             delayThread = new Thread(this);
             delayThread.run();
             // Initialise the number of rooms and the GuestList :        
            noOfRooms =  numberIn;
            guests  = new GuestList(noOfRooms);
            // Graphics settings:     
            setTitle("Hotel");     
            setLayout(new FlowLayout());
           // etc. etc.
           // etc. etc.
           setVisible(true);
        // A run method to delay the program opening:
        public void run()
             try
                  delayThread.sleep(10000);
             catch(InterruptedException ie)
                  ie.printStackTrace();
        }Now, maybe a better way to do this would be to move the setVisible statement from the constructor to the run method.
    Maybe there is an even better mechanism for producing a delay in a program's opening.
    But I'm still curious as to why the main thread was delayed by a delay in what is really an entirely separate thread.
    Any ideas ?
    Edited by: KonTiki on 16-Feb-2013 13:10
    Edited by: KonTiki on 16-Feb-2013 13:19
    Edited by: KonTiki on 16-Feb-2013 13:20
    Edited by: KonTiki on 16-Feb-2013 13:21
    Edited by: KonTiki on 17-Feb-2013 09:16

    Well, first of all calling a Thread object's run() method just runs the code in the same thread. It doesn't start a new thread -- that's what calling the start() method does.
    And the Thread.sleep() method is a static method, meaning "Make *this* thread sleep for X milliseconds". So calling it on another Thread object doesn't cause that thread to sleep, it causes the current thread to sleep.
    I suggest you should go through the concurrency tutorial from Oracle because you seem to be programming by guesswork here.

  • HttpServletResponse Writer error in LinkedBlockingQueue in separate Thread

    I have a servlet that can process a request and send a response. Needing to process many simultaneous requests, I started using a LinkedBlockingQueue in a separate thread to take requests and process them. The problem comes when I have finished processing and want to send a response to the client. I get a NullPointerException when trying to .flush() or .close() the java.io.Writer associated with the HttpServletResponse.
    Exception in thread "Thread-36" java.lang.NullPointerException   
         at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:747)   
         at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:432)   
         at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:305)   
         at org.apache.coyote.http11.Http11Processor.action(Http11Processor.java:992)   
         at org.apache.coyote.Response.action(Response.java:183)   
         at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:322)   
         at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:293)   
         at org.apache.catalina.connector.CoyoteWriter.flush(CoyoteWriter.java:95)   
         at com.interrupt.bookkeeping.http.BookkeepingSystemFacade.perform(BookkeepingSystemFacade.java:343)   
         at com.interrupt.bookkeeping.http.BookkeepingSystemFacade.run(BookkeepingSystemFacade.java:97)   
         at java.lang.Thread.run(Thread.java:613)What I do is, in the servlet, put the HttpServletRequest and HttpServletResponse into ServletInputParams, a class I made with 2 fields to hold the values (a typed bag), and add that class to the queue in the separate thread. In that separate thread, I take the ServletInputParams, get the request and response and start processing. All processing and parameter access in the request works fine, but sending a response using the HttpServletResponse's java.io.Writer gives me the error abouve. Again, this exact same processing works fine if I don't pass the HttpServletResponse between threads.
    Has anyone tackled this problem before? I am using javac 1.5.0_07 and this code is running in Tomcat 5.5. Below is a snippet from the separate thread class, 'BookkeepingSystemFacade' that accepts the servlet parameters. Thanks for any help.
         public synchronized void addToQueue(ServletInputParams servlParams) {
              System.out.println(">> PUTTING into the queue > "+ servlParams);
              try {
                   servletQueue.put(servlParams);
         public void run() {
              System.out.println(">> BookkeepingSystemFacade is RUNNING > ");
              try {
                   ServletInputParams siparams = (ServletInputParams)this.servletQueue.take();
                   while(siparams != null) {
                        System.out.println(">> TAKING from queue > "+ siparams);
                        HttpServletRequest sreq = siparams.req;
                        HttpServletResponse sres = siparams.res;
                        this.perform(sreq, sres);
                        siparams = (ServletInputParams)this.servletQueue.take();
                   System.out.println(">> FINISHING thread > ");
        public synchronized void perform(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
             String cmdValue = req.getParameter("cmd");
             String tokenValue = req.getParameter("token");
             String dataValue = req.getParameter("data");
             String idValue = req.getParameter("id");
             IResult result = new GResult();
             //** return
         resp.setContentType("text/xml");
         Writer writer = resp.getWriter();
         writer.write(result.toXML());
         writer.flush();
         writer.close();
        }

    Sorry to resurrect and old thread but I was experiencing the same problem today and thought I'd share my solution. It seems like it's not possible to pass the response/request objects to different threads because Tomcat automatically spawns a new thread for every HttpRequest.
    I found this out here:
    http://74.125.93.132/search?q=cache:EP6LGWbrVisJ:cs.gmu.edu/~offutt/classes/642/slides/642Lec05a-ServletsMore.pdf+HttpServletResponse+concurrency&cd=1&hl=en&ct=clnk&gl=ca
    "Tomcat creates a separate thread for each HTTP request"
    So it looks like Tomcat is doing our work for us and we don't need to worry about concurrency in dealing with multiple requests simultaneously. So I think an easy solution is to simply call the "run()" method in your code manually.

Maybe you are looking for

  • Third party sales issue

    hi experts,       can any body explain in third party sales where do we see migo, miro, if possible step by step process. thanks in advance

  • Error while connecting to Oracle in Linux

    I wrote a JAVA program to test the connection with Oracle. It worked in NT environment, but it did not in Linux Environment. I got the error message: "IO exception: The Network Adapter could not establish the connection." Here is JAVA code: import ja

  • Library Snippets and your approach to use on a page

    Hello, More of a philosophical question today. Recently I started using Qtip for my hover bubbles (or whatever they're called ) and I needed to add a couple of links: <script src="http://code.jquery.com/jquery-1.3.2.min.js"></script> <script type="te

  • Like in the apple store

    I am this is a simple thing I am just missing on how to do it. I noticed in the Apple store on one of the screen was a long oval with 3 or 4 icons that you click and you go right to that application and this wasn't the dock, it was centered on the sc

  • Do we have request_firmware() kind of support in Solaris

    I need to copy firmware from userspace to kernel space. In linux a native kernel function request_firmare() does that. Does Solaris support this kind of function. Any other suggestions to do this activity are also welcome. Thanks nbsingh