Starting Multiple Threads

I am writing a Java Multi-Threaded application which will listen to SonicMQ and pull messages off a queue. Here is some of the code which I am using to do this.
This code is from one class which I call a QueueManager:
//*** this line instantiates the QueueHandler which will read message off the queue
QueueHandler queueHandler = new QueueHandler(connect,queueReceive,queueSend);
//*** iterate through this loop and create x number of threads
for(int i = 1 ; threads >= i ; i++)
System.out.println("i=" + i);
Thread counterThread = new Thread(queueHandler);
counterThread.setName("mythread_" + i);
counterThread.start();
I am not sure if this is the right way to go about creating multiple threads. By passing in the name of 'mythread' + the variable i, I want to see which thread is getting which messages of my message queue. So, when I first get into QueueHandler ... I do get the current threadname.
public void run()
Thread runthread = Thread.currentThread();
strMyThreadName = runthread.getName();
System.out.println("QueueHandler: run: entering: threadname: " + strMyThreadName);
getConnection();
This works to get me my current threadname ... I get the output which looks correct.
However, when I am getting the messages and printing out the threadname, I get the name of the last thread.
Anyways, am I correct in trying to start 10 records in my loop in 'QueueManager' or is there a better way to do this?
Thanks.
Tom

I solved my old problem, and here is what I did:
In my QueueManager class I changed the code to this:
for(int i = 1 ; threads >= i ; i++)
//*** notice, I am passing in the threadname, and other parameters into the constructor
QueueHandler queueHandler = new QueueHandler("mythread_" +i,connect,queueReceive,queueSend);
Now, in the class QueueHandler, I changed the constructor to this:
//*** Get Connection, and the send and receive queue names
QueueHandler(String prm_threadname,javax.jms.QueueConnection prm_connect,String prm_rQueue,String prm_sQueue)
//*** I take the parameters I passed in and assigned them to class attributes
connect = prm_connect;
rQueue = prm_rQueue;
sQueue = prm_sQueue;          
strMyThreadName = prm_threadname;
//*** I then use this code to create a new thread based on this instance, and this starts the NEW thread on this new object.
runthread = new Thread(this, strMyThreadName);
System.out.println("New Thread=" + runthread + " threadname=" + strMyThreadName);
//*** now by calling Start, the run method will then start on this instance.
runthread.start();
I'm no expert at Java multi-threaded apps, and I am always learning, but I hope this code helps someone else out. Of course, if someone else has a better more elegant way of doing what I want to do, then I definitely want to learn.
Thanks.
Tom

Similar Messages

  • How to protect the creation of a db across multiple threads/processes?

    Given a multi-process, multi-threaded application, and one database file to be created, how can I guarantee that only one of the threads in one of the processes successfully creates the database, when ALL of the threads are going to either attempt to create it, or open it (if it already exists) upon startup?
    My current logic for all threads is:
    set open flags to DB_THREAD
    start transaction
    attempt to open the db
    if ENOENT
    abort transaction
    change open flags to DB_CREATE | DB_EXCL | DB_THREAD
    retry
    else if EEXIST
    abort transaction
    change open flags to DB_THREAD
    retry
    else if !ok
    # some other error
    end
    commit transaction
    I'm testing on Linux right now, with plans to move to Windows, AIX, and Solaris. What I'm experiencing on Linux is several of the threads (out of 10 threads I'm testing) will succeed in creating the database. The others will receive either either succeed in opening the first time through, or will receive the EEXIST when they do the open w/ create flags - ultimately, they open the same created db (I'm presuming the last one that's created by one of the other threads). Effectively, the open with DB_CREATE | DB_EXCL is not ensuring that only one DB is created. I was under the impression that opening in a transaction would guarantee this, but it does not, or maybe I'm doing something incorrectly?
    Should DB_CREATE | DB_EXCL and opening in a transaction guarantee that only one thread can create the database? Do I need to use another synchronization method?
    Note: I am running off of a local disk, not over NFS or anything like that.
    I tried taking out my transaction and using DB_AUTO_COMMIT instead, still no go - multiple threads still report they successfully created the DB. Using BDB 4.5.
    Thanks,
    Kevin Burge

    Brian,
    Thanks for the reply. I think I'm doing what you said, unless I'm misunderstanding. I do have all threads try to do the DB_CREATE | DB_EXCL. Are you saying I shouldn't use the DB_EXCL flag?
    The problem I was seeing with 10 threads calling open w/ DB_CREATE | DB_EXCL on the same db:
    * Between 1 and 9 threads would return success from db->open with the creation flags.... but the last one to create "wins".
    * All the other threads would get EEXIST, as expected.
    The threads that "lost", do get a successful return code from "open" with the create flags, but all data written to them is lost. They act normally except for the fact that the have a deleted file-handle that they are writing to. There's no indicator that records written to them are going into the void.
    My test:
    I had 10 threads each trying to create or open a recno db, then append 10 records, for a total of 100 records expected. Ultimately, I would end up with between 20 to 100 records in the db, depending on how many of the threads said they successfully created the db. So, if 5 threads said they created the db successfully, then 40 records would be missing, because 4 of those threads were writing to deleted file handles. If 2 threads said they created the db, then 10 records would be missing....If 8 threads, then 70 records missing, etc.
    In other words, multiple threads creating the db appears to work correctly, because there are no errors. It was the missing records that caught my attention, and prompted my question on this forum.
    For what it's worth, I've worked around the problem by opening a similarly named file via the open() system call, with O_CREAT|O_EXCL, which is guaranteed to be atomic. The first thread that can create this temp file is the only thread that can actually create the db - all others sleep upon open with ENOENT until it's created.
    Thanks,
    Kevin

  • Problem with ioinning multiple Threads

    Hi,
    I have multiple sub Threads T1, T2, T3.... started by main Thread T. After starting each sub Thread, I stored them in the HashMap. When finish starting all Threads, I want to join each sub Thread to my main Thread.
    The problem is when T3 join with T, it hanged forever! Here is my code:
    class MyThread extends Thread
    private name;
    MyThread(String tName)
    name = tName;
    public void run()
    // doing something....
    public HashMap startThreads()
    HashMap tList = new HashMap();
    for (int i=0; i<5; ++i)
    String tName = "Thread" + i;
    MyThread myT = new MyThread(tName);
    myT.start();
    tList.put(tName, myT);
    public void joinThreads(HashMap tList)
    Iterator iter = tList.values().iterator();
    while (iter.hasNext())
    Thread activeThread = (Thread)iter.next();
    if (activeThread.isAlive()) {
    System.out.println("Join alive thread " + activeThread.tName);
    activeThread.join();
    In my method:
    ... doing s/t
    HashMap tMap = startThreads();
    joinThreads(tMap);
    ... doing s/t else (never excecuted!!!)
    My purpose is staring multi Threads at the same time and executing some code after they all die.
    If I join my sub Thread right after creating it, then the other sub Thread couldn't started until subThread 1 dies!
    If I don't join the sub Thread but remove it from the thread Map when it's not alive then my code executed perfectly. I want to apply join method with my mutiple Threads, how ????
    Could some one give me a hint? Thanks.

    Hi,
    What I don't understand here is why the main Thread
    does not join all the sub Threads ?If you're getting a ConcurrentModificationException while iterating the list of threads, then that's why.
    Why main Thread
    has to wait for sub Thread 1 to finish before joinning
    next sub Threads?It has to join all of the threads. That means it has to wait for all of them to finish. In order to wait for all of the threads it has to wait for the first thread.
    I'm 100% sure that my sub Threads in
    the threadList are valid and alive since I already
    veriffied with other methods.I don't see what that has to do with your problem.
    I already set my joinThreads method as synchronized,
    how come I still have ConcurrentModificationException?Because the list was modified concurrently.
    How can I fix this error?Stop modifying the list concurrently. You haven't posted all of the relevant code, so I can't offer any clues about how to do that.

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

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

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

  • Multiple threads access the same method.

    Hello,
    I have been trying for a long time to find out multiple threads access the shared data.
    I have written a sample code, there I my intention is that method has to be accessed
    onlny one thread at a time., mean one thread finished the job, then next thread can
    access the shared source. But for this code I am not getting the desired out put what I want. But if I am using synchronized block I am getting the output. Please correct where I got mistake. Please see my code.
    public class TestThread implements Runnable {
         Shared r;
         public TestThread() {
              r = new Shared();
         public static void main(String args[]) {
              Thread t1 = new Thread(new TestThread());
              Thread t2 = new Thread(new TestThread());
              t1.setName("A");
              t2.setName("B");
              t1.start();
              t2.start();
          * (non-Javadoc)
          * @see java.lang.Runnable#run()
         @Override
         public void run() {
              // TODO Auto-generated method stub
              r.count();
    class Shared {
         public synchronized void count() {
              String name = Thread.currentThread().getName();
              System.out.println(name + ":accessed...");
              try {
                   for (int i = 0; i < 5; i++) {
                        System.out.println(name + ": " + i);
              } catch (Exception e) {
                   // TODO: handle exception
    }Thanks
    Bhanu lakshmi.

    It depends on what you synchronize. Non-static methods synchronize on the object, so if you're using several objects, you'll be able to call each from their own thread.
    Make your method synchronized or use only a single object and see the difference.

  • Can multiple threads write to the database?

    I am a little confused from the statement in the documentation: "Berkeley DB Data Store does not support locking, and hence does not guarantee correct behavior if more than one thread of control is updating the database at a time."
    1. Can multiple threads write to the "Simple Data Store"?
    2. Considering the sample code below which writes to the DB using 5 threads - is there a possibility of data loss?
    3. If the code will cause data loss, will adding DB_INIT_LOCK and/or DB_INIT_TXN in DBENV->open make any difference?
    #include "stdafx.h"
    #include <stdio.h>
    #include <windows.h>
    #include <db.h>
    static DB *db = NULL;
    static DB_ENV *dbEnv = NULL;
    DWORD WINAPI th_write(LPVOID lpParam)
    DBT key, data;
    char key_buff[32], data_buff[32];
    DWORD i;
    printf("thread(%s) - start\n", lpParam);
    for (i = 0; i < 200; ++i)
    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));
    sprintf(key_buff, "K:%s", lpParam);
    sprintf(data_buff, "D:%s:%8d", lpParam, i);
    key.data = key_buff;
    key.size = strlen(key_buff);
    data.data = data_buff;
    data.size = strlen(data_buff);
    db->put(db, NULL, &key, &data, 0);
    Sleep(5);
    printf("thread(%s) - End\n", lpParam);
    return 0;
    int main()
    db_env_create(&dbEnv, 0);
    dbEnv->open(dbEnv, NULL, DB_CREATE | DB_INIT_MPOOL | DB_THREAD, 0);
    db_create(&db, dbEnv, 0);
    db->open(db, NULL, "test.db", NULL, DB_BTREE, DB_CREATE, 0);
    CreateThread(NULL, 0, th_write, "A", 0, 0);
    CreateThread(NULL, 0, th_write, "B", 0, 0);
    CreateThread(NULL, 0, th_write, "B", 0, 0);
    CreateThread(NULL, 0, th_write, "C", 0, 0);
    th_write("C");
    Sleep(2000);
    }

    Here some clarification about BDB Lock and Multi threads behavior
    Question 1. Can multiple threads write to the "Simple Data Store"?
    Answer 1.
    Please Refer to http://docs.oracle.com/cd/E17076_02/html/programmer_reference/intro_products.html
    A Data Store (DS) set up
    (so not using an environment or using one, but without any of the DB_INIT_LOCK, DB_INIT_TXN, DB_INIT_LOG environment regions related flags specified
    each corresponding to the appropriate subsystem, locking, transaction, logging)
    will not guard against data corruption due to accessing the same database page and overwriting the same records, corrupting the internal structure of the database etc.
    (note that in the case of the Btree, Hash and Recno access methods we lock at the database page level, only for the Queue access method we lock at record level)
    So,
    if You want to have multiple threads in the application writing concurrently or in parallel to the same database You need to use locking (and properly handle any potential deadlocks),
    otherwise You risk corrupting the data itself or the database (its internal structure).
    Of course , If You serialize at the application level the access to the database, so that no more one threads writes to the database at a time, there will be no need for locking.
    But obviously this is likely not the behavior You want.
    Hence, You need to use either a CDS (Concurrent Data Store) or TDS (Transactional Data Store) set up.
    See the table comparing the various set ups, here: http://docs.oracle.com/cd/E17076_02/html/programmer_reference/intro_products.html
    Berkeley DB Data Store
    The Berkeley DB Data Store product is an embeddable, high-performance data store. This product supports multiple concurrent threads of control, including multiple processes and multiple threads of control within a process. However, Berkeley DB Data Store does not support locking, and hence does not guarantee correct behavior if more than one thread of control is updating the database at a time. The Berkeley DB Data Store is intended for use in read-only applications or applications which can guarantee no more than one thread of control updates the database at a time.
    Berkeley DB Concurrent Data Store
    The Berkeley DB Concurrent Data Store product adds multiple-reader, single writer capabilities to the Berkeley DB Data Store product. This product provides built-in concurrency and locking feature. Berkeley DB Concurrent Data Store is intended for applications that need support for concurrent updates to a database that is largely used for reading.
    Berkeley DB Transactional Data Store
    The Berkeley DB Transactional Data Store product adds support for transactions and database recovery. Berkeley DB Transactional Data Store is intended for applications that require industrial-strength database services, including excellent performance under high-concurrency workloads of read and write operations, the ability to commit or roll back multiple changes to the database at a single instant, and the guarantee that in the event of a catastrophic system or hardware failure, all committed database changes are preserved.
    So, clearly DS is not a solution for this case, where multiple threads need to write simultaneously to the database.
    CDS (Concurrent Data Store) provides locking features, but only for multiple-reader/single-writer scenarios. You use CDS when you specify the DB_INIT_CDB flag when opening the BDB environment: http://docs.oracle.com/cd/E17076_02/html/api_reference/C/envopen.html#envopen_DB_INIT_CDB
    TDS (Transactional Data Store) provides locking features, adds complete ACID support for transactions and offers recoverability guarantees. You use TDS when you specify the DB_INIT_TXN and DB_INIT_LOG flags when opening the environment. To have locking support, you would need to also specify the DB_INIT_LOCK flag.
    Now, since the requirement is to have multiple writers (multi-threaded writes to the database),
    then TDS would be the way to go (CDS is useful only in single-writer scenarios, when there are no needs for recoverability).
    To Summarize
    The best way to have an understanding of what set up is needed, it is to answer the following questions:
    - What is the data access scenario? Is it multiple writer threads? Will the writers access the database simultaneously?
    - Are recoverability/data durability, atomicity of operations and data isolation important for the application? http://docs.oracle.com/cd/E17076_02/html/programmer_reference/transapp_why.html
    If the answers are yes, then TDS should be used, and the environment should be opened like this:
    dbEnv->open(dbEnv, ENV_HOME, DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_TXN | DB_INIT_LOG | DB_RECOVER | DB_THREAD, 0);
    (where ENV_HOME is the filesystem directory where the BDB environment will be created)
    Question 2. Considering the sample code below which writes to the DB using 5 threads - is there a possibility of data loss?
    Answer 2.
    Definitely yes, You can see data loss and/or data corruption.
    You can check the behavior of your testcase in the following way
    1. Run your testcase
    2.After the program exits
    run db_verify to verify the database (db_verify -o test.db).
    You will likely see db_verify complaining, unless the thread scheduler on Windows weirdly starts each thread one after the other,
    IOW no two or ore threads write to the database at the same time -- kind of serializing the writes
    Question 3. If the code will cause data loss, will adding DB_INIT_LOCK and/or DB_INIT_TXN in DBENV->open make any difference?
    Answer 3.
    In Your case the TDS should be used, and the environment should be opened like this:
    dbEnv->open(dbEnv, ENV_HOME, DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_TXN | DB_INIT_LOG | DB_RECOVER | DB_THREAD, 0);
    (where ENV_HOME is the filesystem directory where the BDB environment will be created)
    doing this You have proper deadlock handling in place and proper transaction usage
    so
    You are protected against potential data corruption/data loss.
    see http://docs.oracle.com/cd/E17076_02/html/gsg_txn/C/BerkeleyDB-Core-C-Txn.pdf
    Multi-threaded and Multi-process Applications
    DB is designed to support multi-threaded and multi-process applications, but their usage
    means you must pay careful attention to issues of concurrency. Transactions help your
    application's concurrency by providing various levels of isolation for your threads of control. In
    addition, DB provides mechanisms that allow you to detect and respond to deadlocks.
    Isolation means that database modifications made by one transaction will not normally be
    seen by readers from another transaction until the first commits its changes. Different threads
    use different transaction handles, so this mechanism is normally used to provide isolation
    between database operations performed by different threads.
    Note that DB supports different isolation levels. For example, you can configure your
    application to see uncommitted reads, which means that one transaction can see data that
    has been modified but not yet committed by another transaction. Doing this might mean
    your transaction reads data "dirtied" by another transaction, but which subsequently might
    change before that other transaction commits its changes. On the other hand, lowering your
    isolation requirements means that your application can experience improved throughput due
    to reduced lock contention.
    For more information on concurrency, on managing isolation levels, and on deadlock
    detection, see Concurrency (page 32).

  • How do you disable "Run with Multiple Threads" in a standalone EXE

    I have a program written in Labview 6.1.  After moving to a different hardware platform, my program has started crashing at the same point every time it is run.  I eventually found out that the cause of the crash is the fact that the new hardware has a dual core processor.  I confirmed this by disabling "Run with multiple threads" and now the program works fine.  What I need to know now is how to disable the same setting in a built EXE file, since as far as I know the "Run with multple threads" setting only affects execution in the Labview Dev environment.
    Thanks for any help,
    Dave

    Greg McKaskle once posted that using a non-reentrant (VI is NOT re-entrant) wrapper VI to make the calls to the dll will prevent simultaneous execution of the dll.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Executors.newSingleThreadScheduledExecutor() creating multiple threads?

    While examining a stack trace this morning, I found approximately 250 idle threads labelled "pool-4-thread-###", where ### ranged from 1 to 250 or so.
    I then traced pool-4-thread to a ScheduledExecutorService and underlying ThreadPoolExecutor object created via a call to Executors.newSingleThreadScheduledExecutor().
    There are two types of tasks scheduled on that instance of the Executor. The first is a task which runs twice a day. The second type is something that gets scheduled as the result of a user action, which may occur dozens of times a day.
    Under what conditions can a SingleThreadScheduledExecutor create and leave around multiple threads?
    Thanks in advance,
    Mike Benveniste

    If the thread never completes.
    It's either hanging, or, more likely, has an exit condition that's never being met. Or it's spawning processes that are not completing.
    Simply put a debug statement at the beginning and end of the thread so you can see when (and if) it's starting and stopping.
    You may want to use object.killProcess() prior to starting the next instance to force the previous instance to stop if it still exists.
    bcf

  • Help with running multiple threads

    I'm new to programming with threads. I want to know how to run
    multiple threads at the same time. Particularly for making games
    in Java which I'm also begining to learn. For running multiple
    threads at the same time, do you have to put two run() methods
    in the source? If not then how do you make two threads or more
    run at the same time?
    Thanks for helping.

    For running multiple
    threads at the same time, do you have to put two run()
    methods
    in the source? Hi there,
    Each thread is presumably performing a task. You may be performing the same task multiple times or be performing different tasks at once. Either way, each task would typically be contained within the run() method of a class. This class would either be a subclass of java.lang.Thread (extends Thread) or would be an implementation of java.lang.Runnable (implements Runnable). In either case, you would define a method with signature (public void run()...). The difference comes into play when you wish to actually perform one of these tasks. With a subclass of Thread, you would simply perform:
    new MyTask().start();
    With an implementation of Runnable, you would do this:
    new Thread(new MyTask()).start();
    This assumes you don't need to monitor the threads, won't be sending any messages to your tasks or any such thing. If that were the case, you would need to tuck away those returns to new MyTask() for later access.
    In order to launch two threads simultaneously, you would have something along the lines of:
    new MyTask().start();
    new MyOtherTask().start();
    Now it is perfectly possible that MyTask() would complete before MyOtherTask() managed to start in which case it wouldn't appear as if you had actually had multiple threads running, but for non-trivial tasks, the two will likely overlap. And of course, in a game, these tasks would likely be launched in response to user input, which means that you wouldn't have any control over when or in what order they executed.
    Anyhow, it's as simple as that. You should also consider following the Java Threading trail which shows a simple example of using multiple threads. You can find it at:
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    Regards,
    Lynn

  • Confused: multiple thread on multiple instances

    I was trying to see if multiple threads, each running a different instance of a given class which has a (non-static) synchronized method will force a wait on each thread even though its a different instance. So, I put togeteher the following test class and am now more confused.
    First the code.
    package test;
    import java.util.Date;
    public class TestThreads implements Runnable{
         public TestThreads() {
         private synchronized void synchedMethod(long msToWait){
              String myThread = Thread.currentThread().getName();
              System.out.println(new Date() +" synchedMethod(" + msToWait +") " +myThread);
              try {
                   wait(msToWait);
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public void run() {
              synchedMethod(1000);
         public static void main(String[] args) {
              Thread[] tt = new Thread[5];
              for (int i = 0; i < tt.length; i++) {
                   tt[i] = new Thread(new TestThreads());
              for (int i = 0; i < tt.length; i++) {
                   tt.run();
    Now, in addition to my original unanswered question, why are all the threads showing as being the same?
    Thank you;
    nat

    As already noted you must start() threads - run() is just a normal method call in the current thread.
    To answer you question: each object has a distinct monitor lock. If every thread calls the synchronized method of a different instance then no thread will ever find that the lock of its instance is unavailable. Any Java language text that covers threading and synchronization will tell you this.

  • JMeter +JSF 1.2 +Multiple threads issue

    I have an issue when running JMeter with an JSF 1.2 application.
    I have the regex and xpath fix working. It is extracting the correct ViewState value, but only as long as I am running one thread. If I start a thread group with multiple threads the regex/xpath will eventually return the default value and the test will fail.
    Scenario 1 (SUCCESS):
    I run one thread and one thread group, regex/xpath return the
    "ViewState" value correctly and the test runs perfectly until I stop it.
    Scenario 2 (FAILURE):
    I run multiple threads and one thread group, regex/xpath
    eventually return the DEFAULT value instead the "ViewState" value to
    all but one thread. The more threads the faster they fail. It really
    seems like there is a threading issue.
    Has anyone experienced similar issues when running regex/xpath and multiple threads?

    Thank you, I tried what you suggested and revealed something interesting. The application in some cases prints the following on the screen:
    *~com.sun.faces.saveStateFieldMarker~*, and it is in those cases JMETER Xpath extraction fails.
    Well I have to look more into it. Thank again for the help.

  • Can multiple threads use same transaction concurrently?

              Is it possible that same transaction is being used by multiple threads concurrently
              in WLS? If each thread is doing suspend and resume how does it work? Does the
              transaction implementation support it? Is there a way to do it?
              

    Why you don't tell us some more about your application?
              I'm assuming this is a relatively long running transaction if run
              serially. One common solution is to break this type of workflow into
              several separate transactions with queues between them.
              -- Rob
              Karambir Singh wrote:
              > Is there any workaround for this? I mean to something like explicitly associating
              > the txn with user created threads.
              >
              > "krishna" <[email protected]> wrote:
              >
              >>Transaction context cannot be propagated to user created Threads.
              >>-Krishna
              >>"Karambir Singh" <[email protected]> wrote in message
              >>news:[email protected]...
              >>
              >>>I'm starting a transaction in main thread and this thread spawns three
              >>
              >>threads.
              >>
              >>>I want updates done in main transaction and updates done in three child
              >>
              >>threads
              >>
              >>>to be part of the same transaction. The transaction is finally commited
              >>
              >>by
              >>main
              >>
              >>>thread.
              >>>
              >>>
              >>>
              >>>
              >>>
              >>>"Dimitri I. Rakitine" <[email protected]> wrote:
              >>>
              >>>>What are you trying to do ?
              >>>>
              >>>>Karambir Singh <[email protected]> wrote:
              >>>>
              >>>>
              >>>>>Is there any workaround to do this?
              >>>>
              >>>>>"Dimitri I. Rakitine" <[email protected]> wrote:
              >>>>>
              >>>>>>No, it is associated with a thread which started it.
              >>>>>>
              >>>>>>Karambir Singh <[email protected]> wrote:
              >>>>>>
              >>>>>>
              >>>>>>>Is it possible that same transaction is being used by multiple
              >>
              >>threads
              >>
              >>>>>>concurrently
              >>>>>>
              >>>>>>>in WLS? If each thread is doing suspend and resume how does it
              >>
              >>work?
              >>
              >>>>>>Does the
              >>>>>>
              >>>>>>>transaction implementation support it? Is there a way to do it?
              >>>>>>
              >>>>>>--
              >>>>>>Dimitri
              >>>>>>
              >>>>
              >>>>--
              >>>>Dimitri
              >>>>
              >>>
              >>
              >
              

  • Creating multiple Threads in applets

    Hi, I need some help creating multiple threads in applets. If you look at the simple code example below you�ll see that it uses one thread that calls the findTarg() method that gives its sleep() a value and makes the oval find its new target.
    What I want to know is how do I create a new thread in this applet? � So for example I could call a findTarg2() method from within a new thread that sets its sleep() to a faster or slower value and starts at the same time as findTarg().
    Hope that makes sense.
    <applet code="thread.class" height=400 width=400>
    </applet>
    import java.awt.Graphics;
    import java.awt.*;
    import java.awt.event.*;
    public class thread extends java.applet.Applet implements Runnable {
    int x = 200;
    int y = 200;
    int xTarg;
    int yTarg;
    int sleeper;
    boolean go;
    Thread first;
    public void start(){
    if(first == null); {
    first = new Thread(this);
    first.start();
    public void run(){
    while (first != null) {
    findTarg();
    try {
    Thread.sleep(sleeper);
    } catch (InterruptedException e) { }
    public void findTarg(){    
    if(go == true){
    sleeper = 10;
    if(x < xTarg)x++;
    if(x > xTarg)x--;
    if(y < yTarg)y++;
    if(y > yTarg)y--;
    repaint();
    if((x == xTarg)&&(y == yTarg))go = false;
    public boolean mouseDown(Event evt, int x, int y) {
    xTarg= x;
    yTarg= y;
    go = true;
    return true;
    public void paint(Graphics g) {
    g.setColor(Color.black);
    g.fillOval(x,y,20,20);
    }

    I've found another example and this time it extends JApplet. I'm sorry I can't help you more, but I'm new as well.
    // Fig. 15.7: RandomCharacters.java
    // Demonstrating the Runnableinterface
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RandomCharacters extends JApplet
    implements Runnable,
    ActionListener {
    private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private JLabel outputs[];
    private JCheckBox checkboxes[];
    private final static int SIZE = 3;
    private Thread threads[];
    private boolean suspended[];
    public void init()
    outputs = new JLabel[ SIZE ];
    checkboxes = new JCheckBox[ SIZE ];
    threads = new Thread[ SIZE ];
    suspended = new boolean[ SIZE ];
    Container c = getContentPane();
    c.setLayout( new GridLayout( SIZE, 2, 5, 5 ) );
    for ( int i = 0; i < SIZE; i++ ) {
    outputs[ i ] = new JLabel();
    outputs[ i ].setBackground( Color.green );
    outputs[ i ].setOpaque( true );
    c.add( outputs[ i ] );
    checkboxes[ i ] = new JCheckBox( "Suspended" );
    checkboxes[ i ].addActionListener( this );
    c.add( checkboxes[ i ] );
    public void start()
    // create threads and start every time start is called
    for ( int i = 0; i < threads.length; i++ ) {
    threads[ i ] =
    new Thread( this, "Thread " + (i + 1) );
    threads[ i ].start();
    public void run()
    Thread currentThread = Thread.currentThread();
    int index = getIndex( currentThread );
    char displayChar;
    while ( threads[ index ] == currentThread ) {
    // sleep from 0 to 1 second
    try {
    Thread.sleep( (int) ( Math.random() * 1000 ) );
    synchronized( this ) {
    while ( suspended[ index ] &&
    threads[ index ] == currentThread )
    wait();
    catch ( InterruptedException e ) {
    System.err.println( "sleep interrupted" );
    displayChar = alphabet.charAt(
    (int) ( Math.random() * 26 ) );
    outputs[ index ].setText( currentThread.getName() +
    ": " + displayChar );
    System.err.println(
    currentThread.getName() + " terminating" );
    private int getIndex( Thread current )
    for ( int i = 0; i < threads.length; i++ )
    if ( current == threads[ i ] )
    return i;
    return -1;
    public synchronized void stop()
    // stop threads every time stop is called
    // as the user browses another Web page
    for ( int i = 0; i < threads.length; i++ )
    threads[ i ] = null;
    notifyAll();
    public synchronized void actionPerformed( ActionEvent e )
    for ( int i = 0; i < checkboxes.length; i++ ) {
    if ( e.getSource() == checkboxes[ i ] ) {
    suspended[ i ] = !suspended[ i ];
    outputs[ i ].setBackground(
    !suspended[ i ] ? Color.green : Color.red );
    if ( !suspended[ i ] )
    notify();
    return;
    }

  • Breaking a Program Execution into Multiple Threads

    Hi,
    We want to run a BAPI with Differenet parameters synchronoulsy in the same program as the BAPI is taking a very lon time for execution.
    We are Planning to break up the execution and the call o the BAPI into multiple threads that can run synchronously. How can this concept implemented in SAP ABAP.
    Thanks in advance.
    Arunava

    I am using parallel processing in my current client. Basis define a dialog processes group that we can use. This way our program will be limited to the number of processing give in the group. For example, our production system has 5 servers and each servers has 15 dialog processes. Basis reserve in the group 5 dialog processes for each group. So when we run our program, we are limited to 25 processes. We use function module SPT_INITIALIZE to find out the number of dialog processes and free processes for our group.
    The logic of the program as follow:
    Do loop
        Call function module with starting new task and destination in group performing end of task subroutine
    Enddo
    Wait until all task completed (check help on wait-you need to keep track of the number of record completed)
    In end of task subroutine, use command receive results from function to get the return parameters.
    Hope this helps.
    Cheers

  • Synchronize work from multiple threads using wait() and notifyAll() help

    Hello folks,
    (Sorry for my bad english)
    My current project handles multiple access requests to a shared collection from multiple threads originating from different classess and methods. Therefor I need to keep track of the order in which the Threads access that collection. I wrote a sort of Buffer class that has a static instance entry which initiate a new Instance of my Buffer class, attributes the instance a cue number and return the instance to the caller Thread.(Just like when you go to a supermarket and draw a number to wait to get served at the cheese counter).The callerThread then uses this instance to execute a method within the buffer class. Inside the buffer class method, I want to set a while loop on wait() just like this:
    while(currentCue != myCueState)
    wait();
    when all other prior method calls within my Buffer class are done, the loop should wake up using a notifyAll() call and check the condition "currentCue != myCueState" agen to see if its turn has come.
    I am new to the wait() and notifyAll() stuff and are therefor not sure what I am dooing wrong here: The only way this buffer class finishes all it's cues is when the caller Threads are beeing executed in the same order than they have checked in to the Buffer class. Otherwise I get some sort of dead-lock in the middle. Here is my code for the Buffer class:
    public class Buffer{
        private static int currentCue = 0;
        private static int lastCued = 0;
        private int myCueState;
        private Buffer myInstance = null;
        synchronized void doTaskOne(){      
            try{
                while(currentCue != myCueState)
                    wait();           
                //Do your task now
                System.out.println("doTaskOne got Executed: "+currentCue);
                currentCue++;
                notifyAll();
            catch(Exception a){}
        synchronized void doTaskTwo(){
             try{
                while(currentCue != myCueState)
                    wait();
                //Do your task now
                System.out.println("doTaskTwo got Executed: "+currentCue);
                currentCue++;
                notifyAll();
            catch(Exception a){}
        synchronized void doTaskThree(){
            try{
                while(currentCue != myCueState)
                    wait();          
                //Do your task now
                System.out.println("doTaskThree got Executed: "+currentCue);
                currentCue++; 
                notifyAll();
            catch(Exception a){}
        synchronized Object getSomething(){
            try{                   
                while(currentCue != myCueState)
                    wait();           
                //Do your task now
                System.out.println("getSomething got Executed");
                currentCue++;
                notifyAll();
            catch(Exception a){}
            return "something";
        //Access the buffer class through a single static synchronized instance and draw a turn number
        public synchronized Buffer instance(){
            myInstance = new Buffer();
            myInstance.setMyCueState();
            return myInstance;
        private void setMyCueState(){
             myCueState = lastCued;
             lastCued++;
    }and here for the Test class I have coded to test this:
    public class TestBuffer{
         private Buffer accessOne;
         private Buffer accessTwo;
         private Buffer accessThree;
         private Buffer accessFour;
         public TestBuffer(){
                    //Instantiate different instances from Bufferclass and draw a number
              accessThree = new Buffer().instance();
              accessOne = new Buffer().instance();
              accessTwo = new Buffer().instance();          
              accessFour = new Buffer().instance();
              Thread one = new Thread(){
                   public void run(){
                        accessOne.doTaskOne();
              Thread two = new Thread(){
                   public void run(){
                        accessTwo.doTaskTwo();
              Thread three = new Thread(){
                   public void run(){
                        accessThree.doTaskThree();
              Thread four = new Thread(){
                   public void run(){
                        accessFour.getSomething();
              try{               
                   one.start();                    
                   two.start();
                   three.start();     
                   four.start();                         
              catch(Exception f){}
         public static void main(String args[]){
              TestBuffer myTest = new TestBuffer();
    }What am I doing wrong here??
    Maby this is not how I should use the notifyAll() method, but how then?
    Please give me a solution!
    Thanks

    Ok, so if I get you guys right, the following should do it:
    public class Buffer{
        private static Object sharedLock = new Object();
        public void doTaskOne(){      
              synchronized(sharedLock)  {
                System.out.println("doTaskOne got Executed: ");
        public void doTaskTwo(){
             synchronized(sharedLock)  {
                System.out.println("doTaskTwo got Executed: ");
        public void doTaskThree(){
             synchronized(sharedLock)  {
                  System.out.println("doTaskThree got Executed: ");
        public Object getSomething(){
            synchronized(sharedLock)  {
                System.out.println("getSomething got Executed");
                return "something";
    }Lets say that each method accesses the same ressources (in this case a table model) to retreave values, delete rows and set some existing values vith new values and all this 20-30 times a minute, all processing will stay synchronised and collision is not possible?
    And lets say I would update the Table model directly from the buffer Class using MyTableModel.instance().setValueAt() or watever methods I implemented on my Table model, could I safely do that using "SwingUtilities.invokeLater();" from my BufferClass just like this:
    public void doTaskThree(){
            synchronized(sharedLock)  {
                   Runnable runme = new Runnable(){
                         public void run(){
                                MyTableModel.instance().setValueAt("abc", 5,5);  
                   SwingUtilities.invokeLater(runme);
    }Thanks in advance for your help guys!

Maybe you are looking for

  • Can't move an application out of the applications folder to a different location?

    I had a couple of applications in the applications folder that I thought would be better suited on the desktop, but evertime I tried dragging the application to the desktop (or any other location on my Mac for that matter) it only seemed to create a

  • Info on report painter

    hi all, We have a requirement of report painter in our project.Any help in thei regard is highly appreciated. Any docs giving the basics of report painter is highly appreciated. Regards, Rajashree

  • Installing windows xp problems

    I got a new mbp after my old one died. Finally got my hands on a copy of windows. I have done this install before. I loaded boot camp, made the part, then restarted etc into windows install. Came to format part, however only one appeared, and didnt t

  • Audiobook downloaded but cant get it on my iphone

    I downloaded  an audiobook but it wont transfer onto my i phone .Tried syncing a few times  but nothing happening .Do i need to do something different with an audiobook . Thanks

  • Question on "exporting to QT"

    When I export to QT movie, I get my usual Final Cut Pro movie. This particular movie I'm working is my first HD movie. For some unknown reason, when I export to QT movie, not only do I get my usual Final Cut Pro movie, I also get 9 other files which