Thread executer

i have a list of task that is currently running sequentially.
each task is independent of one another.
what i want to do is to execute these tasks in threads (each task run in a thread)
but i want to limit the number of thread running (ie. only five thread may running..when one is finished, another thread may start running untill all thread in a list is done)
Is there some class that let me do this?
if there isn't any, can someone tell me what this thread problem be called (ie..countdown latch, blocking queue)
so i can google and try to implement it

You can try things like.
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future future = executor.submit(new Runnable() {
            public void run() {
        future.get();
        Future<String> futureCall = executor.submit(new Callable<String>() {
            public String call() throws Exception {
                return "Hello world";
        String result = futureCall.get();

Similar Messages

  • Thread execute

    hi, What is the significance of following 1. thread execte number 2. execute queue length 3. execute queue throughput

    executeThreadCount is the number of JVM threads available for concurrently executing
    requests (usually JSPs and servlets).
    executeQueueLength is the number of requests waiting for an executeThread to become
    available.
    executeQueueThroughput is the number of requests processed per second.
    sunil <[email protected]> wrote:
    hi, What is the significance of following 1. thread execte number
    2. execute queue length 3. execute queue throughput

  • Problem with very simple 2 threads java application

    Hi,
    As fa as i'm concerned this is a thread licecycle:
    1. thread created: it is dead.
    2. thread started: it is now alive.
    3. thread executes its run method: it is alive during this method.
    4. after thread finishes its run method: it is dead.
    No I have simple JUnit code:
    public void testThreads() throws Exception {
    WorkTest work = new WorkTest() {
    public void release() {
    // TODO Auto-generated method stub
    public void run() {
    for (int i=0;i<1000;i++){
    log.debug(i+":11111111111");
    //System.out.println(i+":11111111111");
    WorkTest work2 = new WorkTest() {
    public void release() {
    // TODO Auto-generated method stub
    public void run() {
    for (int i=0;i<1000;i++){
    log.debug(i+":22222222222");
    Thread workerThread = new Thread(work);
    Thread workerThread2 = new Thread(work2);
    workerThread.start();
    //workerThread.join();
    workerThread2.start();
    //workerThread2.join();
    And
    public interface WorkTest extends Runnable {
    public abstract void release();
    And that's it..
    On the console I see 999 iterations of both threads only if i uncomment
    //workerThread.join();
    //workerThread2.join();
    In other case I see random number of iterations - JUNIT finishes and Thread1 made 54 and Thread2 233 iterations - the numbers are different every time i start the JUnit..
    What I want? Not to wait until the first one finishes - I want them to start at the same time and they must FINISH their tasks...
    Please help me asap :(

    This is very simple... Look at your code:
    workerThread.start();
    workerThread.join();
    workerThread2.start();
    workerThread2.join();What are you doing here? You start the first thread, then you call join(), which waits until it finishes. Then after it's finished, you start the second thread and wait until it finishes. You should simply do this:
    workerThread.start();
    workerThread2.start();
    workerThread.join();
    workerThread2.join();I.e., you start the 2 threads and then you wait (first for the first one, then for the second one).

  • How to monitor/examine threads usage in WebLogic Server?

    Hi,
    I need to monitor andd examine the usage of the threads (execute, non-blocking
    execute, etc.) in my WebLogic Server (WLS) instance (5.1 SP10 on Solaris 2.6)
    so that I can check that multi-threading is being used by WLS when executing methods
    on some objects.
    I have looked at the WLS Console but it does not seem to give any useful info
    on this. I have used OptimizeIt during the development on NT and know that it
    gives some info on threads usage but am not sure if it will do the job on a Solaris
    box with 1000's of requests hitting WLS.
    Has anybody done something similar and/or recommend any tips/tool?
    Many thanks in advance.

    On solaris, do
    kill -3 <weblogic_process_id>
    You will get a thread dump to standard error of the WebLogic process. Usually
    this is all you need to know.
    Mike
    "Michel Dinh" <[email protected]> wrote:
    >
    Hi,
    I need to monitor andd examine the usage of the threads (execute, non-blocking
    execute, etc.) in my WebLogic Server (WLS) instance (5.1 SP10 on Solaris
    2.6)
    so that I can check that multi-threading is being used by WLS when executing
    methods
    on some objects.
    I have looked at the WLS Console but it does not seem to give any useful
    info
    on this. I have used OptimizeIt during the development on NT and know
    that it
    gives some info on threads usage but am not sure if it will do the job
    on a Solaris
    box with 1000's of requests hitting WLS.
    Has anybody done something similar and/or recommend any tips/tool?
    Many thanks in advance.

  • How to start two threads at the same time

    Hi there,
      I want to include multithreading in the CVI program. I have two tasks which has no dependence between them, so I would like to start two threads for perform the tasks. I follow the introduction http://www.ni.com/white-paper/3663/en/ to start my code. In my code, I add a command button, when it is pressed, I create two threads to perform the tasks. In each task, I have a big loop and in each iteration, I use ProcessSystemEvents to avoid no response on system message. But it doesn't work actually, the program suspended. I wonder must I initialize the threads in main. I am looking for a way to start the threads in the callback function for a button since I am not starting those threads at the beginning but while it is triggered.
    the main frame of the code looks
    int CVICALLBACK Test1(void *functionData)
    { int i=0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK Test2(void *functionData)
    int i = 0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK cmdcb(int panel, int control, int event, void *callbackData, int eventData1, int eventData2)
    { int threadID1, threadID2;
    if (event==EVENT_COMMIT)
    SetPanelAttribute(panelHandle, ATTR_DIMMED, 1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test1, NULL, &threadID1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test2, NULL, &threadID2);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID1, 0);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID2, 0);
    return 0;
    Attachments:
    TestThread.zip ‏239 KB

    In my opinion your threads may be simply lasting longer than expected due to an incorrect sleep policy of threads paired with with ProcessSystemEvents () in the loop.
    I made up a quick example that shows this behaviour: playing with "Do not sleep" and "Call ProcessSystemEvents" options you can see how threads execute.
    BTW: do not forget to release the thread function IDs at the end of functions.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    thread.zip ‏7 KB

  • Error while using threads in proc program

    Hi,
    I am getting the error fetched column value NULL (-1405) in proc program while using the threads.
    The execution of the program is as follows.
    Tot_Threads = 5 (Total threads, totally 5 records with value instance names)
    No_Of_threads = 1 (No Of threads executed at the same time)
    Example :
    INSTANCE_NAME – Link1, link2, link3, link4, link5 (All different Databases)
    NO_OF_THREADS - 5
    Threading Logic:
    Based on the maintanence NO_OF_THREADS, the program will process.
         If (NO_OF_THREADS == 0)
              Process_Sequence
         else
              if NO_OF_THREADS == TOT_THREADS
                   Process_Type1
              else
                   Process_Type2
    In a loop for all different instances,
    New context area will be created and allocated.
         New oracle session will be created.
         New structure will be created and all global parameters are assigned to that structure.
         For each instance, a new thread will be created (thr_create) and all the threads will call
         the same(MainProcess) function which takes the structure as parameter.
         At the end of every session, the corresponding oracle session will logged out.
    Process_Type1 logic :
         /* For Loop for all threads in a loop */
         for(Cnt=0;Cnt < Tot_Threads;Cnt++)
              /* Allocating new contect for every different thread */
              EXEC SQL CONTEXT ALLOCATE :ctx[Cnt];
              /* Connected to new oracle session */
              logon(ctx[Cnt],ConnStr);          
    /* Assigning all the global parameters to the structure and then passing it to InsertBatching function */
              DataSet[Cnt].THINDEX=Cnt;
              DataSet[Cnt].sDebug=DebugMode;
              strcpy(DataSet[Cnt].THNAME,(char *)InsNameArr[Cnt].arr);
              DataSet[Cnt].ctx=ctx[Cnt];
              /* creating new threads for time in a loop */
    RetVal = thr_create(NULL,0,InsertBatching,&DataSet[Cnt],THR_BOUND,&threads[Cnt]);
              sprintf(LocalStr1,"\nCreated thread %d", Cnt);
              DebugMessage(mptr,LocalStr1,DebugMode);
         for(Cnt=0;Cnt <Tot_Threads;Cnt++)
              /* Waiting for threads to complete */
              if (thr_join(threads[Cnt],NULL,NULL))
                   printf("\nError in thread Finish \n");
                   exit(-1);
              /* Logout from the specific oracle session */     
              logoff(ctx[Cnt]);
              /* Free the context area after usage */
              EXEC SQL CONTEXT FREE :ctx[Cnt];     
    used functions:
              thr_create with thr_suspend option
              thr_join to wait for the thread to complete
    Process_Type2 logic :
         Here the idea is , if the load is heavy , then we can change the maintanence of NO_OF_THREADS (Ex - 2), so that only two threads will be executed in the same time , others should wait for      the same to complete ,once the first two threads completed and the next two should be started and then in the same manner it will do for all the threads.
    The parameters passing and the structure passing are same as above.
    Here all threads will be created in suspended mode, and then only No_Of_threads(2) will
    be started, others will be in suspended mode, once the first two is completed then the
    other two thread will be started and in the same manner other threads.
         used functions:
              thr_create with thr_suspend option
              thr_continue to start the suspended thread
              thr_join to wait for the thread to complete
    Process_Sequence logic :
    Here the idea is , to run the program for all the instances , without creating the threads.Hence in the for loop , one by one instance will be taken and call the same function to Process. This will call the same function repeated for each different value. The parameters passing and the structure passing are same as above.
         The InsertBatching function will prepare the cursor and pick all records for batching and then , it will call other individual functions for processing. For all the functions the structure variable will be passed as parameter which holds all the neccessary values.
    Here in all the sub functions , we have used
         EXEC SQL CONTEXT USE :Var;
         Var is corresponding context allocated for that thread, which we assume that the corresponding context is used in all sub functions.
         EXEC SQL INCLUDE SQLCA;
    This statement we have given in InsertBatching Function not in all sub functiosn
    Example for the Sub functions used in the program :-
    /* File pointer fptr and dptr are general file pointers , to write the debub messages, DataStruct will hold all global parameters and also context area .
    int Insert(FILE fptr,FILE dptr,DataStruct d1)
    EXEC SQL BEGIN DECLARE SECTION;
         VARCHAR InsertStmt[5000];
    EXEC SQL END DECLARE SECTION;
    char LocalStr[2000];
    EXEC SQL CONTEXT USE :d1.ctx;
    InsertStmt will hold insert statement      
    EXEC SQL EXECUTE IMMEDIATE :InsertStmt;
    if (ERROR)
         sprintf(LocalStr,"\nError in Inserting Table - %s",d1.THNAME);
         DebugMessage(dptr,LocalStr,d1.sDebug);
         sprintf(LocalStr,"\n %d - %s - %s",sqlca.sqlcode,ERROR_MESG,d1.THNAME);
         DebugMessage(dptr,LocalStr,d1.sDebug);
         return 1;
    return 0;
    I get this error occationally and not always. While preparing the sql statement also i am getting this error.
    The code contains calls to some stored procedures also.
    Thanks in advance

    in every select nvl is handled and this error is occuring while preparing statements also

  • Lack of randomness in my threads

    Hi, I have the following code:
    import java.util.Collections;
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Iterator;
    public class ThreadSafeCollection {
         public static void main(String args[]) throws Exception {
              List queue = Collections.synchronizedList(new LinkedList());
              LinkedList threads = new LinkedList();
              int i = 0;
              while(i < 25) {
                   threads.add(new InsertMessages("Thread" + i, queue));
                   i++;
              Iterator iterator = threads.iterator();
              while(iterator.hasNext()) {
                   ((InsertMessages)iterator.next()).start();
              Thread.sleep(2000);
              System.out.println("threads contains " + threads.size());
              System.out.println("queue contains " + queue.size() + " items.");
    class InsertMessages extends Thread {
         List queue;
         final static int maxIterations = 10;
         public InsertMessages(String threadName, List queue) {
              super(threadName);
              this.queue = queue;
         public void run() {
              int iterations = 0;
              try {
                   Thread.sleep((int)Math.random() * 1000);
              catch(InterruptedException e) {
                   System.err.println("something");               
              while(iterations < maxIterations) {
                   queue.add(getName() + " at iteration " + iterations);
                   iterations++;                    
    This above code produce the following results for the queue:
    Thread0 at iteration 0, Thread0 at iteration 1, Thread0 at iteration 2, Thread0 at iteration 3, Thread0 at iteration 4, Thread0 at iteration 5, Thread0 at iteration 6, Thread0 at iteration 7, Thread0 at iteration 8, Thread0 at iteration 9, Thread1 at iteration 0, Thread1 at iteration 1, Thread1 at iteration 2, Thread1 at iteration 3, Thread1 at iteration 4, Thread1 at iteration 5.....
    My problem is that the Thread execute in order from 1 to 10. This seems very deterministic. I expected more randomness. i.e. I expected the order of thread execution to be something like this: Thread3, Threads8, Thread1, Thread7... Any ideas why this is happening?
    Thanks,
    Paul0al

    This is happening because you are inserting the threads into this list, then you are starting them in the same order. So one starts, runs, sleeps, the second starts, runs, sleeps, etc... So of course they go in order. However, if you left it running a long time, it's not impossible that due to factors beyond your control, one thread might sleep a little longer or shorter and therefore cause the threads to start running in different orders, but even that will likely remain in the same different order for some period of time.
    If you really are wanting to start them in any order, then put the threads in a collection that doesn't guaranty an order (like Hashtable) and then get an iterator and start them. The other thing to do would be to start threads and have the sleep time be some random value each time to.

  • Thread pool executor problem

    When using a thread pool executor (java.util.concurrent.ThreadPoolExecutor) to limit the number of threads executing at a time, the number of threads running still exceeds the limit number.
    This is the code:
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 20, TimeUnit.SECONDS, new LinkedBlockingQueue());
    The number of tasks in my program are 4, so i always have 4 threads running, although i limited it to 3.
    Can anyone help me with this problem? Or can u propose another solution to limit the number of running threads? By the way, i also tried using a newFixedThreadPool() and got the same problem.
    Thx.

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • The problem in the thread pool implemented by myself

    Hello, I need to a thread pool in J2ME CDC 1.0 + FP 1.0, so I implemented a simple one by myself that also meets my own requirement.
    Here is the main idea:
    The thread pool creates a fixed number of threads in advance. When a task comes, it is put in the waiting list. All threads tries to get the tasks from the waiting list. If no task exists, the threads wait until someone wakes them up.
    Here are the requirements from myself:
    1. when a task has finished its work in one execution, it is put in the waiting list for the next run.
    2. the task can control the delay between when the task owner tries to put it in the waiting list and when the task is actually put in the waiting list. I need this function because sometimes I don't want the tasks to run too often and want to save some CPU usage.
    In my program, I creates two thread pools. In one pool, every task don't use the delay, and the thread pool works very well. The other pool has the tasks that use the delay, and sometimes, as I can see from the printed information, there are many tasks in the waiting list but 0 or 1 thread executes tasks. It seems that the waiting threads cannot wake up when new tasks comes.
    I suspect the code in addTask(), but cannot find the reason why it fails. Could anyone please help me find out the bug in my code? I put the code of thread pool below
    Thank you in advance
    Zheng Da
    ThreadPool.java
    package j2me.concurrent;
    import java.util.LinkedList;
    import java.util.Timer;
    import java.util.TimerTask;
    import alvis.general.Util;
    public class ThreadPool {
         private int maxQueueSize;
         private boolean running = true;
         private Thread[] threads;
         private LinkedList tasks = new LinkedList();
         private Timer timer = new Timer(true);
         private AtomicInteger usingThreads = new AtomicInteger(0);
         private synchronized boolean isRunning() {
              return running;
         private synchronized void stopRunning() {
              running = false;
         private synchronized PoolTask getTask() {
              while (tasks.isEmpty() && isRunning()) {
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              if (tasks.isEmpty())
                   return null;
              // Util.log.info(Thread.currentThread().getName() +
              // " gets a task, left tasks: " + tasks.size());
              return (PoolTask) tasks.removeFirst();
         private synchronized void addTaskNoDelay(PoolTask task) {
              tasks.addLast(task);
              notifyAll();
         private synchronized void addTask(final PoolTask task) {
              long delay = task.delay();
              if (delay == 0) {
                   addTaskNoDelay(task);
              } else {
                   timer.schedule(new TimerTask() {
                        public void run() {
                             addTaskNoDelay(task);
                   }, delay);
         private synchronized int numTasks() {
              return tasks.size();
         private class PoolThread extends Thread {
              public void run() {
                   Util.poolThreads.inc();
                   while (isRunning()) {
                        PoolTask task = getTask();
                        if (task == null) {
                             Util.poolThreads.dec();
                             return;
                        usingThreads.inc();
                        long currentTime = System.currentTimeMillis();
                        task.run();
                        long elapsedTime = System.currentTimeMillis() - currentTime;
                        if (elapsedTime > 100)
                             System.err.println(task.toString() + " takes " + ((double) elapsedTime)/1000 + "s");
                        usingThreads.dec();
                        if (!task.finish()) {
                             addTask(task);
                   Util.poolThreads.dec();
         public ThreadPool(int size, int taskQueueSize) {
              maxQueueSize = taskQueueSize;
              threads = new Thread[size];
              for (int i = 0; i < threads.length; i++) {
                   threads[i] = new PoolThread();
                   threads.start();
         public synchronized boolean executor(PoolTask task) {
              if (!isRunning()) {
                   return false;
              Util.log.info("Thread Pool gets " + task + ", there are "
                        + numTasks() + " waiting tasks");
              if (numTasks() >= maxQueueSize) {
                   return false;
              addTask(task);
              return true;
         public synchronized void destroy() {
              stopRunning();
              timer.cancel();
              // TODO: I am not sure it can wake up all threads and destroy them.
              this.notifyAll();
         public synchronized void printSnapshot() {
              System.err.println("using threads: " + usingThreads + ", remaining tasks: " + tasks.size());
    PoolTask.javapackage j2me.concurrent;
    public interface PoolTask extends Runnable {
         * It shows if the task has already finished.
         * If it isn't, the task will be put in the thread pool for the next execution.
         * @return
         boolean finish();
         * It shows the delay in milliseconds that the task is put in the thread pool.
         * @return
         long delay();

    are receiving/sends tasks packets time consuming operation in your case or not? if it is not you do not need to use thread pools at all. you can create a queue like in your code through the linked list and dispatch this queue periodically with minimum monitor usage. try this.
    import java.util.LinkedList;
    public class PacketDispatcher extends Thread {
        LinkedList list = new LinkedList();
        public PacketDispatcher (String name) {
            super(name);
        public void putTask(Task task) {
            synchronized (list) {
                list
                        .add(task);
                list.notify();
        public void run() {
            while (true/* your condition */) {
                Task task = null;
                synchronized (list) {
                    while (list.isEmpty())
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    task = (Task)list
                            .poll();
                if (task == null) {
                    try {
                        Thread
                                .sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    continue;
                task
                        .run();
                if (!task.isFinished()) {
                    putTask(task);
                Thread
                        .yield();
        public static void main(String[] args) {
            // just for test
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            PacketDispatcher dispatcher = new PacketDispatcher("Packet Dispatcher");
            Task task = new Task();
            dispatcher.putTask(task);
            dispatcher.start();
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            Task task2 = new Task();
            dispatcher.putTask(task2);
    class Task {
        long result = 0;
        public boolean isFinished () {
            if (getResult() >= 10000000) {
                return true;
            return false;
        public void run() {
            for (int i = 0; i < 1000; i++) {
                result += i;
        public long getResult () {
            return result;       
    }

  • Wait() releases ALL of the waiting thread's monitors?

    When wait() is called from a synchronized bock, it is my understanding that the current thread releases the monitor it was holding (which was the monitor of the object that was being synchronized on.)
    What is confusing me is my testing of this code:
       public synchronized Object lock() {
          synchronized(lockObj) {
             if (bLocked) {
                try { lockObj.wait();}
                catch (Exception e) { e.printStackTrace(); }
           bLocked = true;
           return someObject;
       }When this method is called by Thead A and he has to wait, I can see where Thread A will release his lock of lockObj. However, the whole method is synchronized, (meaning, against this), and lock() is waiting and hasn't finished executing yet. I suspected Thread B wouldn't be able to call lock(), because Thread A should still have a monitor for this. But Thread B can- which must mean that when Thread A goes into wait(), he gives up all his monitors across the board, not just the one in immediate involvement (the one for lockObj, in this case)?
    P.S., forget what this code is supposed to accomplish- i wrote it trying to understand the monitor states.
    Thanks!

    I notice that the lock() method is not a static method. So everything depends on how you are testing this code sample. You haven't included that in your posting.
    What I suspect is:
    You are having your threads access two DIFFERENT instances of the object who owns the method lock(). This means that your threads are NOT competing for executing the lock() method on the SAME object.
    lockObj.wait() releases the lock on the lockObj ONLY. wait() does not release locks on all monitors owned by the thread executing the wait().
    What you are trying to prove can be understood easily by using static synchronized methods.
    If your lock() method is static synchronized, you will find that a Thread B can't enter the lock() method at all. Why? Because Thread A has only released the lock on the lockObj. It STILL holds the lock on the class level monitor. When did Thread A obtain this? When it entered the lock() method. Unless Thread A releases the class level monitor, by doing
    xyz.class.wait();
    in the lock() method, any other Thread B will simply wait to enter the lock() method.
    To carry the discussion further, when another thread, say Thread C, does a xyz.class.notify(), Thread B is woken up first and enters the lock() method. Thread A will return from the xyz.class.wait() only after Thread B quits the lock() method.

  • Limited threads are created for my databse connection

    Hi,
    I have my web applicaton running with the mysql as my database. some part of my application has jsps retrieving and displaying some data(I am right now moving the data retrieval part in jsp to bean classes). Till I complete the work on beans I will have my jsps calling the connection and executing the task.
    The following is the bean that gets connection to DB
    package con;
    import java.beans.*;
    import java.io.Serializable;
    import java.sql.*;
    import java.util.*;
    public class Myconn extends Object implements Serializable {
       public Connection con;
       public Connection getConnected() {
           connection();
            return con;
    public void connection()
                 try
                   Class.forName("com.mysql.jdbc.Driver");
                   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?jdbcCompliantTruncation=false&zeroDateTimeBehavior=convertToNull", "mydb", "data");
                 catch(SQLException e)
                     System.out.println(e);
                     catch(ClassNotFoundException e){
                       System.out.println("unable to load"+ e);
    }The problem is when I check the mysql administrator always it shows only 5 active threads executing 5 queries at an instance(application will be simultaneously used by more than 50 users) also if one thread(which means query) takes more time then it pulls other threads also and this slows down my application.
    in my jsps I call the bean as below:
    <jsp:useBean id="mycon" class="con.Myconn"/>
    Connection connection = mycon.getConnected() ();
             statement = connection.createStatement();
    .any help on this please

    Your example was a bit confusing, but here are some tips:
    - If you have one database server, yes, running multiple queries on it will probably make each one slower than if only one were running.
    - Are you creating a new thread for every query? Try making a thread pool so that you only have X number of queries at once, but none of them need to reconnect, which takes time.
    - In the end, you may need to optimize your database.
    Can you give a better example of what exactly is going wrong?

  • Using AsyncEventHandlers as a RTJ buildin thread pool

    Hi David
    1. I would like to use AsyncEventHandler mechanism as a thread pool. Would there be a way in future version to access the AsyncEventHandler's RT Thread pool API ?
    2. I am using the BoundAsyncEventHandler for long duration task (since the BoundAsyncEventHandler is bound to a specific Thread) - Would there be a way in future version to bound a specific RT Thread to this handler ? - for example a RT Thread that was created by my own Thread pool ?
    Thanks

    Gabi wrote:
    1.We need our code to access the AEH's "thread pool" and check the pool's availability; increase/decrease the pool size dynamically; check pool size for enough free threads to run any given number of tasks and so on...There are no API's for this. How a VM supports AEH execution is an implementation detail, and while a "pool" is the logical form of implementation the details can vary significantly so there's no real way to define an API to control it without defining what form it must take. For example in Java RTS the pool threads are initially at the highest system priority and then drop down to the priority of the AEH they execute. In a different design you might have a pool of threads per priority level (or set of priority levels) so even the notion of increasing/decreasing the pool size is not necessarily straight-forward. In Java RTS the pool will grow as needed to service outstanding AEH activations. You can control the initial number of threads - and there are two pools: one of heap-using and one for non-heap AEH.
    2. I was thinking about adding the BAEH class with the next method:
    void setBoundThread(RTThread t) throws IllegalArgumentExceptionand also in the Ctor add the RTThread as a parameter.
    Inside this method, the thread should be check if started and is so should throw an IllegalArgumentException.Sure, but why do you need to do this? What is different about the RTT that you pass in? The thread executing an AEH acquires the characteristics of the AEH.
    An API like this raises some questions such as: when would the thread be started? It also has a problem in that the run() method of the thread has to know how to execute an AEH, which means we'd (the RTSJ expert group) probably have to define a class BoundAEHThread that has a final run() method and you'd then subclass it.
    3. Additional question, what do you think about using lock (CountdownLatch) during the AEH's executions ?
    I've seen somewhere that AEH should only be used for short live tasks - is it true ? (in the JavaDoc it says there is no problem doing so but I want to be sure)If an AEH blocks for any length of time and additional AEH are activated then the pool management overhead may increase (unless you already sized it appropriately). But otherwise there's no restriction on what the code in an AEH can do. But note that none of the java.util.concurrent synchronization tools support priority-inversion avoidance, so you need to be careful if using them (ie only use them across threads of the same priority and don't expect FIFO access).
    David Holmes

  • Are queries thread-safe?  (read on)

    I have a singleton class in a multithreaded environment. This singleton has a single private instance for each database query being used.
    For parameterized queries, the argument vector is passed into the session.executeQuery() call when a thread executes a query.
    My question is: Do the DatabaseQuery (subclasses) objects change state once they are "set up", or does the session simply READ what it needs from a query, and bind any parameters outside of the query object?
    I would like to avoid having to instantiate a query object every single time the query needs to be executed. Reuse would save a lot of performance headaches.
    Thanks,
    Bret

    Not only need you only instantiate a query once, but after you execute it for the first time TopLink doesn't need to prepare it again either.
    That is the benefit to using parameters. Each time the SQL is the same but the query is different.

  • Multi-threaded undercutting of dual locks in TestSTand 3.0

    Group,
        I have a test sequence that is running 16 threads to test radios.  About midway into my testing one of the threads will some how take priority and will not wait for another thread to finish its testing.  The first time a thread executes a series of tests all is fine.  But when the second or later thread attempts to run the same code it is always stops waiting for the thread that is one dual lock ahead of it.  Let me setup the condition.  Assume Thread 1 is just finished with Lock Audio and Thread 2 begins executing Lock Audio.  At some point in the middle of the dual locks sequence, Thread 1 takes priority and begins running its test leaving Thread 2 having not finished its set of tests within the dual locks.  In fact, thread 2 is unable to do anything until thread one has gone completely through its entire sequence file.  How can one thread countermand the previous thread.  Example of testing below:
    Lock Audio
    Lock PortAA
       Take a measurement
    UnLock PortAA
    Lock PortAA
       Take a measurement
    UnLock PortAA
    UnLock Audio
    Lock VolumeMax
    Lock PortAA
       Take a measurement
    UnLock PortAA
    Lock PortAA
        Take a measurement
    Unlock PortAA
    UnLock VolumeMax
    ..........etc..............

    Did you mean to have an unlock audio in the middle? It seems odd that Port AA is sometimes used under the audio lock and sometimes not. It makes me think you might not really be locking/unlocking the locks that you intended to.

  • How do I cancel an operation in Pro*C (with threads)

    I would like to be able to cancel a potentially long running Oracle operation initiated in Pro*C. It seems that, in an application having only a single database connection (i.e. does not use EXEC SQL ENABLE THREADS), I can do this by sending the SIGINT signal from another thread -- since obviously the DB thread is blocked waiting for the operation to complete. By having the "cancel thread" execute a pthread_kill(tid, SIGINT) against the blocked thread the operation is cancelled and the requisite Oracle error (ORA-01013) is caught.
    However, it seems that once I enable threads, this method stops working. Unfortunately, the application I am writing needs multiple database threads. More dismal, I need to direct the cancellation to a single thread. I can, of course, direct the SIGINT to a thread via pthread_kill, but it does not work. Even a single thread with a single DB connection ignores the attempt to cancel -- in fact the program I wrote to test my initial theory stopped working (well, stopped canceling the operation) immediately just by adding an EXEC SQL ENABLE THREADS call.
    So...does anyone know a call that I can make, from within another thread, that would cause an operation (executing on a given database context (sql_context) to become cancelled? Or does anyone have any other suggestions that I may experiment with?
    Thanks all! Looking forward to any ideas.
    OS: AIX 5.3
    DB: Oracle 10g

    Well, while I am still unsure why enabling threads renders my original solution incapable, I have found a suitable working solution.
    After some research, I came across the OCIBreak call in the Oracle Call Interface. Mating this with the Pro*C functions to get the environment and service contexts (SQLEnvGet and SQLSvcCtxGet) allows me to call it. So, currently I set a SIGALRM signal handler and use pthread_kill in the monitoring thread to fire it off. The signal handler eventually calls OCIBreak.
    I am hoping I can get rid of the signal handler and directly call OCIBreak from within the the monitoring thread itself -- but I'm not sure if this will break Oracle's thread consistency model and cause any heart ache. Oracle says that only a single thread should execute commands on a context, so I am not sure if OCIBreak is an exception to that rule. I may just try it and see what happens, but just because it works does not mean it is right or even stable. I'd like definitive proof (or disproof), so if anyone has some insight that'd be welcome.
    Thanks again.
    Edited by: DreamWarrior1337 on Jan 22, 2009 2:53 PM

Maybe you are looking for