Multithreaded Application - How to diagnose

I ran my multi-threaded application and ended up getting this output. my cpu % shoots up to 95% some time after starting my program. Also, I'd like to know how to debug, diagnose multi-threaded application in general. How to do C like trace and other means.
Thanks.
The following is the thread-dump. It was originally for 400 threads. as the char limit exceeded i give here only a portion. And how to attach a file in a post here.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
2010-04-30 20:09:53
Full thread dump Java HotSpot(TM) Client VM (10.0-b22 mixed mode, sharing):
"DestroyJavaVM" prio=10 tid=0xad62a800 nid=0x4690 waiting on condition [0x00000000..0xb7f6b070]
   java.lang.Thread.State: RUNNABLE
"pool-1-thread-400" prio=10 tid=0xb41ff800 nid=0x4835 runnable [0xad5fe000..0xad5fee20]
   java.lang.Thread.State: RUNNABLE
     at java.net.SocketInputStream.socketRead0(Native Method)
     at java.net.SocketInputStream.read(SocketInputStream.java:129)
     at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
     at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
     at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
     - locked <0x8e825398> (a java.io.BufferedInputStream)
     at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
     at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1000)
     - locked <0x8e812d18> (a sun.net.www.protocol.http.HttpURLConnection)
     at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
     at engine.HttpTask.run(HttpTask.java:51)
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
     at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
     at java.lang.Thread.run(Thread.java:619)
"pool-1-thread-1" prio=10 tid=0x09d15000 nid=0x46a4 runnable [0xb56bc000..0xb56bce20]
   java.lang.Thread.State: RUNNABLE
     at java.net.SocketInputStream.socketRead0(Native Method)
     at java.net.SocketInputStream.read(SocketInputStream.java:129)
     at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
     at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
     at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
     - locked <0x8e0bc8c0> (a java.io.BufferedInputStream)
     at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
     at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1000)
     - locked <0x8e0bc8f8> (a sun.net.www.protocol.http.HttpURLConnection)
     at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
     at engine.HttpTask.run(HttpTask.java:51)
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
     at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
     at java.lang.Thread.run(Thread.java:619)
"MySQL Statement Cancellation Timer" daemon prio=10 tid=0x09ce3400 nid=0x46a0 in Object.wait() [0xb5721000..0xb57220a0]
   java.lang.Thread.State: WAITING (on object monitor)
     at java.lang.Object.wait(Native Method)
     - waiting on <0x8c702bd0> (a java.util.TaskQueue)
     at java.lang.Object.wait(Object.java:485)
     at java.util.TimerThread.mainLoop(Timer.java:483)
     - locked <0x8c702bd0> (a java.util.TaskQueue)
     at java.util.TimerThread.run(Timer.java:462)
"Low Memory Detector" daemon prio=10 tid=0x09a5dc00 nid=0x469d runnable [0x00000000..0x00000000]
   java.lang.Thread.State: RUNNABLE
"CompilerThread0" daemon prio=10 tid=0x09a53000 nid=0x469c waiting on condition [0x00000000..0xb5a4dad8]
   java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" daemon prio=10 tid=0x09a51c00 nid=0x469b waiting on condition [0x00000000..0x00000000]
   java.lang.Thread.State: RUNNABLE
"Finalizer" daemon prio=10 tid=0x09a4d000 nid=0x469a in Object.wait() [0xb5cef000..0xb5ceff20]
   java.lang.Thread.State: WAITING (on object monitor)
     at java.lang.Object.wait(Native Method)
     - waiting on <0x8c6b8870> (a java.lang.ref.ReferenceQueue$Lock)
     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:116)
     - locked <0x8c6b8870> (a java.lang.ref.ReferenceQueue$Lock)
     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:132)
     at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
"Reference Handler" daemon prio=10 tid=0x09a48800 nid=0x4699 in Object.wait() [0xb5d40000..0xb5d40da0]
   java.lang.Thread.State: WAITING (on object monitor)
     at java.lang.Object.wait(Native Method)
     - waiting on <0x8c6b88f8> (a java.lang.ref.Reference$Lock)
     at java.lang.Object.wait(Object.java:485)
     at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
     - locked <0x8c6b88f8> (a java.lang.ref.Reference$Lock)
"VM Thread" prio=10 tid=0x09a47400 nid=0x4697 runnable
"VM Periodic Task Thread" prio=10 tid=0x09a71400 nid=0x469e waiting on condition
JNI global references: 869
Heap
def new generation   total 4544K, used 830K [0x8c1c0000, 0x8c6a0000, 0x8c6a0000)
  eden space 4096K,   9% used [0x8c1c0000, 0x8c21fb10, 0x8c5c0000)
  from space 448K, 100% used [0x8c5c0000, 0x8c630000, 0x8c630000)
  to   space 448K,   0% used [0x8c630000, 0x8c630000, 0x8c6a0000)
tenured generation   total 60544K, used 39479K [0x8c6a0000, 0x901c0000, 0x901c0000)
   the space 60544K,  65% used [0x8c6a0000, 0x8ed2dce8, 0x8ed2de00, 0x901c0000)
compacting perm gen  total 12288K, used 2177K [0x901c0000, 0x90dc0000, 0x941c0000)
   the space 12288K,  17% used [0x901c0000, 0x903e0518, 0x903e0600, 0x90dc0000)
    ro space 8192K,  73% used [0x941c0000, 0x947a34a0, 0x947a3600, 0x949c0000)
    rw space 12288K,  58% used [0x949c0000, 0x950b8668, 0x950b8800, 0x955c0000)

itsraja wrote:
I ran my multi-threaded application and ended up getting this output. my cpu % shoots up to 95% some time after starting my program. Also, I'd like to know how to debug, diagnose multi-threaded application in general. How to do C like trace and other means. Use a profiler. There are many different ones.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceThis indicates that you are either allocating too much memory, or are leaking memory. The VM will usually consume much cpu just before an OutOfMemoryError due to lots of call to the garbage collector.
Use a memory profiler to see why, and where the problem is.

Similar Messages

  • Multithreading application - how to use correctly if uses network?

    I'm coding "daemon"-like software, which do some things in the loop (login to somewhere, do some things and logout) using multithreading.
    My application run about 1000-2000 threads and this threads do job.
    So here is my htop log at first ~10 minutes:
    http://i.stack.imgur.com/wlaeh.png
    So you can see on the above screenshot that some number of threads is running (ordered by green R status)
    But after some time this happens:
    http://i.stack.imgur.com/xf9Ny.png
    As you can see just one-three threads are running periodically (it seems like system slow down threads or make it sleeping).
    Application run threads for small-time job (it's about 10 seconds to 1 minute) and after thread die Fixed Thread Pool Executor create new threads to do same job.
    So as I understand it should be equal speed of threads execution at all times. But it slow down after ~10-20 minutes. Normally running threads in htop up to ~500-200-300-100 threads and down to ~3-30-60 threads at each time. But after this 10-20 minutes just only thread is executing. So can you tell me what is happens and how to fix that?
    Or can please anybody contact me at email *[REMOVED BY MODERATOR]* and I'll give source code (it's not big) and *[REMOVED BY MODERATOR]* ?
    Edited by: 907212 on Jan 10, 2012 5:45 PM
    Edited by: EJP on 11/01/2012 14:57: moderated. Don't post your email address in public places; and this is not a rent-a-coder service. Answers should be posted here.

    You don't mention what hardware you are runnng this on and what your software configuration is (os version, java version).
    But unless your are on a really big system you will never get 1000 - to 2000 threads doing anything at the same time.
    The number of threads that can execute simultaneously is mostly governed by hardware related to the number of processors and the number of cores.
    And if a thread isn't one of those that is executing simultaneously then it must be sleeping and not doing any work. With that many threads the biggest percentage of them will always be sleeping.
    Threads that are executing will keep executing until they relinquish control (to wait for some event) to another thread; unless you have implemented a homegrown time-slice mechanism that doles out fixed-interval slices to threads in a round-robin fashion.
    What drove the decision to use so many threads?
    We can provide some suggestions if you give us some information about what the business requirement actually is for your application. Include information about what type of work the threads will actually be doing.
    You included one example of logging in, doing some work, and logging out. How many different systems are you connecting to? Are they all Oracle DBs? How often do you connect/reconnect to the same Oracle DB? Depending on the use case your app could benefit by using a connection pool that keeps connections open; there is a high performance cost for opening/closing/reopening connections.

  • Consuming a jms queue from a multithread application

    Hi
    Thank you for reading my post.
    I have an application which shuld consume message of a queue.
    my application is multithread and what i want to know is:
    - How i can ask queue to remove a message after my thread finished its work with the message, by this way i can ensure that if my thread face an exception after it read the message my message will not lose.
    - As it is multithread application, How i can ensure that a message is not delivered to two or more thread? is there any way to consume the messages in a synchronized way?
    Will synchronized access restrict the performance?
    Thanks

    This is running in a J2DK environment. For my thread pool, I just copied one from a Sun tutorial on multi-threading then modified it. I creaed a seperate package with three classes. Here is my thread pooling package. I basically use a Vector to hold threads when they are not working. And you can set a limit as to the max number of active threads.
    package threadpooling;
    * @author cferris
    *  This class is simple to wrap the runnable
    *  thread for the worker thread around other
    *  needed parameters like salon id and source.
    public class TaskWrapper {
      // Define the needed instance fields.
      public  Runnable taskAtHand = null;
      public  String taskType = "";
        // Overloaded constructor.
        public TaskWrapper(Runnable task) {
          // Just set the runnable
          taskAtHand = task;
          taskType = "WorkerThread";
        }  // of overloaded contructor
        // Overloaded constructor.
        public TaskWrapper(Runnable task, String taskType) {
          // Just set the instance fields
          taskAtHand = task;
          this.taskType = taskType;
        }  // of overloaded contructor
    package threadpooling;
    * @author cferris
    *  This class is for tracking the number of
    *  active threads so we don't go over the set
    *  limit. This class basically synchronizes
    *  the methods that update the active thread
    *  counter.
    import java.util.*;
    public class ThreadPool {
      // Define the instance fields.
      //   First define instance fields for the
      //   management of the thread pools - pm.
      protected Vector poolOfThreads = new Vector();
      private  static LinkedList taskQueue = new LinkedList();
      private  static int poolSize = 0;
      private  static boolean pmAvailable = true;
      private  static boolean daemon = false;
      public   static boolean shutDown = false;
      //   Instance field for the management of
      //   the threads - tm.
      private  static int activeThreads = 0;
      private  static int maxReached = 0;
      private  static int numTimesReached = 0;
      private  static boolean tmAvailable = true;
      // Define constants
      private  static final int MAX_LIMIT_DEFAULT = 32;
        // The constructor.
        public ThreadPool() {
          this(MAX_LIMIT_DEFAULT, false);
        }  // of constructor
        // Overload the constructor with max number of active jobs.
        public ThreadPool(int poolSize, boolean daemon) {
          this.poolSize = poolSize;
          this.daemon = daemon;
          poolOfThreads = new Vector();
          taskQueue = new LinkedList();
          salonTracker = new Vector();
          // Load up and initialize the threads.
          for (int i=0; i < poolSize; i++) {
              Thread thread = new WorkerThread(this, i);
              thread.setDaemon(daemon);
              thread.start();
              poolOfThreads.add(thread);
        }  // of overloaded constructor
        // Overload this method to allow just the runnable task.
        public void assignWork(Runnable work) {
          // Create the wrapper
          TaskWrapper wrapper = new TaskWrapper(work, "A task");
          assignWork(wrapper);
        }  // of overloaded assignWork
        // Push a unit of work (work thread) on the the worker thread.
        public synchronized void assignWork(TaskWrapper work) {
          // First increament the active thread count.
          increment();
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          taskQueue.addLast(work);
          pmAvailable = true;
          notifyAll();
        }  // of assignWork
        // Get the next unit of work (work thread).
        public synchronized TaskWrapper getNextWorkAssignment()  {
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          TaskWrapper nextTask;
          if (!taskQueue.isEmpty())
              nextTask = (TaskWrapper)taskQueue.removeFirst();
          else
              nextTask = null;
          pmAvailable = true;
          notifyAll();    
          return nextTask;
        }  // of getNextWorkAssignment
        // Return the number of tasks waiting on the work queue.
        public synchronized int workWaiting()  {
          // Wait until we can access the linked list 
          try {
              if (!pmAvailable)
                  wait();
          } catch(InterruptedException e) { }
          pmAvailable = false;
          notifyAll();
          int qSize = taskQueue.size();
          pmAvailable = true;
          notifyAll();    
          return qSize;
        }  // of workWaiting
        // Wait until all the tasks have been completed.
        public void waitForCompletion() {
          int prev = 0;
          // Continue checking untill all the threads have
          // completed and been removed.
          while(!poolOfThreads.isEmpty()) {
             // Lets record the difference
             if (poolOfThreads.size() != prev) {
                 System.out.println("waiting for " + poolOfThreads.size() + " to complete");
                 prev = poolOfThreads.size();
             // Loop through the thread pool and check each thread.         
             for (int t = 0; t < poolOfThreads.size(); t++)
                  if (!((WorkerThread)poolOfThreads.get(t)).working)
                      // This thead is done so remove it.
                      poolOfThreads.remove(t);
          }  // of while
        } // waitForCompletion
        // Set the max number of allow threads.
        public synchronized void setPoolSize(int newLimit) {
          // just set the limit.
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          poolSize = newLimit;
          // Reset the max counters/trackers too
          maxReached = 0;
          numTimesReached = 0;
          // Create additional threads in the pool if needed
          if (poolSize > poolOfThreads.size())
              // Load up and initialize the threads.
              for (int i = poolOfThreads.size(); i < poolSize; i++) {
                  Thread thread = new WorkerThread(this, i);
                  thread.start();
                  poolOfThreads.add(thread);
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();       
        }  // of setPoolSize.
        // The method to increment thread counter.
        private synchronized void increment() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool "); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          activeThreads++;
          // Check if this is the highest number of threads
          // that has been active, if not then set so.
          if (activeThreads > maxReached)
              maxReached = activeThreads;
          if (activeThreads == poolSize)
              numTimesReached++;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll(); 
        }  // of increment
        // The method to increment thread counter.
        public synchronized void decrement() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool "); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          activeThreads--;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll(); 
        }  // of decrement
        // A method to determine if the maximum number of active
        // threads has been reached.
        public synchronized boolean limitNotReached() {
          boolean limit = false;
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool."); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          if (activeThreads < poolSize)
             limit = true;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();
          return limit;
        }  // of limitNotReached
        // A method to return the number of active threads.
        public synchronized int currentNum() {
          // Check if available
          while (!tmAvailable) {
             try {
               wait();
             catch(InterruptedException ie) {
               // logger.fatal("Synchronized error in ThreadPool"); 
               // logger.fatal("Error message is: " + ie.getMessage());
               System.exit(5);
          // Ok, lock the object while we update it.
          tmAvailable = false;
          notifyAll();
          int numberOf = activeThreads;
          // Done, now release the object.
          tmAvailable = true;
          notifyAll();
          return numberOf;
        }  // of currentNum
    package threadpooling;
    * @author cferris
    *   This is the work thread that receives the
    *   taskes or unit of work that make up the
    *   thread pool.
    public class WorkerThread extends Thread {
      // Define need instance fields.
      public  boolean working = true;
      public  int id = 0;
      private int pauseFactor = 1;
      // The thread pool that this object belongs to.
      public ThreadPool owner;
      // Define the constructor for the seperate thread.
      public WorkerThread(ThreadPool pooler, int id)  {
        owner = pooler;
        this.id = id;
      }  // of contructor
      //  Wait for work or for system shutdown.
      public void run() {
        // Define the work object. 
        TaskWrapper unitOfWork = null;
        // Wait for work or until system is shutting down.
        do {
           unitOfWork = owner.getNextWorkAssignment();
           if (unitOfWork != null) {
               // First set name and then add salon to watch list.
               String taskName = unitOfWork.taskType + "-" + id;
               setName(taskName);
            // System.out.println("Starting thread - " + getName());
               unitOfWork.taskAtHand.run();
               // Done, now adjust tracker and reset the pause factor.
               owner.decrement();
               pauseFactor = 1;
           else {
               // No work so pause a bit
               try {
                   sleep(150 * pauseFactor);
               } catch (InterruptedException e) { }
               // If consecutively pausing because of no work then
               // increase the pause time up to a point.
               if (pauseFactor < 49)
                   pauseFactor++;
        } while (!owner.shutDown);
        // Set indicator this thread in the pool is done.
        working = false; 
      }  // of run
    }To use the thread pool just create a static instance of the ThreadPool in your main class
      private  static ThreadPool threadPool = new ThreadPool(getMaxThreads(), useDaemon());Then to launch a new thread use this.
        if (runOnSeperateThread()) {  
            WriteTransThread task = new WriteTransThread(messasge);
            // Add to the thread pool.
            threadPool.assignWork(new TaskWrapper(task, "my thread"));
      private boolean runOnSeperateThread() {
        // First check if mutli threading is turned on
        // and if there are open threads.
        if (multiThreadingOn && threadPool.limitNotReached())
            // Yes, there are open threads.
            return true;
        // Check if we can wait for an open thread.
        if (!multiThreadingOn || !waitForOpenThread)
            // No multi threading or waiting allowed.
            return false;
        // OK, wait for an open thread, wait for up
        // to 90 seconds.
        int j = 0;
        do {
            try {
                // Wait 1/2 a second.
                Thread.sleep(500);
            } catch(InterruptedException ignore) { };
            // Check again for an optn thread.
            if (threadPool.limitNotReached())
                // Ok to run on separate thread.
                return true;
            // Increament counter and wait again.
            j++;
        } while(j < 180);
        // If we got this far then we've waited long enough.
        logger.warn("Reached limit on waiting for an open thread in the pool");
        return false;
      }  // of runOnSeperateThreadThe WriteTransThread is a class that will extract the message body and write out its data to a table.
    Last, before you end your program make sure all the threads have competed by calling the following.
      //  If multi-threading is activated then this method will
      //  wait for them to complete before returning. The
      //  max wait time is 300 secs or 5 minutes.
      private void waitForThreadsToComplete(String message) {
        // First check for multi threading. 
        if (prop.useMultiThread() && (threadPool.currentNum() > 0)) {
            int limit = 0;       
            // Some threads are still active, wait
            logger.info("Waiting for threads to complete before " + message
                      + " current thread count is " + threadPool.currentNum());
            do {
               limit++;
               try {
                   Thread.sleep(500);  // Sleep 1/2 a sec.
               } catch(InterruptedException ie) { }  // Ignore the error for now.
               // Max waith is 300 sec or 5 min.
            } while ((threadPool.currentNum() > 0) && (limit < 600));
      }  // of waitForThreadsToComplete
     

  • How to Debug C++ Multithreaded Application in Solaris

    Hi All,
    I am working in Solaris Sparc 5.8 Machine. I need to debug Multithreaded C++ Application in Unix Environment.
    I am using dbx debugger.
    Please explain me how to debug multithreaded applications. if possible please explain me with example.
    Thanks in Advance.
    Thanks & Regards,
    Vasu

    1. Look over the dbx manual that comes with Sun Studio. Dbx includes many features for debugging MT code.
    2. If you have specific questions after reading the manual and trying out the features, ask them in the debugger forum:
    http://forum.sun.com/forum.jspa?forumID=257

  • How to configure ENV and DB for multithreaded application?

    Hi,
    From document, I know DB_THREAD must be checked for both ENV and DB, but , I don't know which one is best choice for multithreaded application while facing DB_INIT_LOCK and DB_INIT_CDB. In my application, there maybe multi readers and writers at the same time, should I use DB_INIT_LOCK instead of DB_INIT_CDB? what other flags should I use?
    DB_INIT_CDB provides multiple reader/single writer access while DB_INIT_LOCK should be used when multiple processes or threads are going to be reading and writing a Berkeley DB database.
    Thanks for your seggestions and answers.

    Thanks for the explanation,
    The Berkeley DB Concurrent Data Store product
    allows for multiple reader/single writer access
    to a database. This means that at any point in time,
    there may be either multiple readers accessing a
    database or a single writer updating the database.
    Berkeley DB Concurrent Data Store is intended for
    applications that need support for concurrent updates
    to a database that is largely used for reading.
    If you are looking to support multiple readers and
    multiple writers then take a look at the Transactional
    Data Store product
    (http://download.oracle.com/docs/cd/E17076_02/html/programmer_reference/transapp.html)
    In this case the Environment is typically opened with:
    DB_INIT_MPOOL, DB_INIT_LOCK, DB_INIT_LOG, and DB_INIT_TXN.
    Let me know if I missed any of your question.
    Thanks,
    Sandra

  • Pro*c multithreaded application has memory leak

    Hi there,
    I posted this message a week ago in OCI section, nobody answer me.
    I am really curious if my application has a bug or the pro*c has a bug.
    Anyone can compile the sample code and test it easily.
    I made multithreaded application which queries dynamic SQL, it works.
    But the memory leaks when i query the SQL statement.
    The more memory leaks, the more i query the SQL statement, even same SQL
    statement.
    I check it with top, shell command.
    My machine is SUN E450, Solaris 8. Oracle 9.2.0.1
    Compiler : gcc (GCC) 3.2.2
    I changed source code which is from
    $(ORACLE_HOME)/precomp/demo/proc/sample10.pc
    the sample10 doesn't need to be multithreaded. But i think it has to work
    correctly if i changed it to multithreaded application.
    the make file and source code will be placed below.
    I have to figure out the problem.
    Please help
    Thanks in advance,
    the make file is below
    HOME = /user/jkku
    ORA = $(ORACLE_HOME)
    CC = gcc
    PROC = proc
    LC_INCL = -I$(HOME)/work/dbmss/libs/include
    lc_incl = include=$(HOME)/work/dbmss/libs/include
    SYS_INCL =
    sys_incl =
    ORA_INCL = -I. \
    -I$(ORA)/precomp/public \
    -I$(ORA)/rdbms/public \
    -I$(ORA)/rdbms/demo \
    -I$(ORA)/rdbms/pbsql/public \
    -I$(ORA)/network/public \
    -DSLMXMX_ENABLE -DSLTS_ENABLE -D_SVID_GETTOD
    INCLUDES = $(LC_INCL) $(SYS_INCL) $(ORA_INCL)
    includes = $(lc_incl) $(sys_incl)
    LC_LIBS =
    SYS_LIBS = -lpthread -lsocket -lnsl -lrt
    ORA_LIBS = -L$(ORA)/lib/ -lclntsh
    LIBS = $(LC_LIBS) $(SYS_LIBS) $(ORA_LIBS)
    # Define C Compiler flags
    CFLAGS += -D_Solaris64_ -m64
    CFLAGS += -g -D_REENTRANT
    # Define pro*c Compiler flags
    PROCFLAGS += THREADS=YES
    PROCFLAGS += CPOOL=YES
    # Our object files
    PRECOMPS = sample10.c
    OBJS = sample10.o
    .SUFFIXES: .o .c .pc
    .c.o:
    $(CC) -c $(CFLAGS) $(INCLUDES) $*.c
    .pc.c:
    $(PROC) $(PROCFLAGS) $(includes) $*.pc $*.c
    all: sample10
    sample10: $(PRECOMPS) $(OBJS)
    $(CC) $(CFLAGS) -o sample10 $(OBJS) $(LIBS)
    clean:
    rm -rf *.o sample10 sample10.c
    the source code is below which i changed the oracle sample10.pc to
    multithreaded application.
    Sample Program 10: Dynamic SQL Method 4
    This program connects you to ORACLE using your username and
    password, then prompts you for a SQL statement. You can enter
    any legal SQL statement. Use regular SQL syntax, not embedded SQL.
    Your statement will be processed. If it is a query, the rows
    fetched are displayed.
    You can enter multi-line statements. The limit is 1023 characters.
    This sample program only processes up to MAX_ITEMS bind variables and
    MAX_ITEMS select-list items. MAX_ITEMS is #defined to be 40.
    #include <stdio.h>
    #include <string.h>
    #include <setjmp.h>
    #include <sqlda.h>
    #include <stdlib.h>
    #include <sqlcpr.h>
    /* Maximum number of select-list items or bind variables. */
    #define MAX_ITEMS 40
    /* Maximum lengths of the names of the
    select-list items or indicator variables. */
    #define MAX_VNAME_LEN 30
    #define MAX_INAME_LEN 30
    #ifndef NULL
    #define NULL 0
    #endif
    /* Prototypes */
    #if defined(__STDC__)
    void sql_error(void);
    int oracle_connect(void);
    int alloc_descriptors(int, int, int);
    int get_dyn_statement(void);
    void set_bind_variables(void);
    void process_select_list(void);
    void help(void);
    #else
    void sql_error(/*_ void _*/);
    int oracle_connect(/*_ void _*/);
    int alloc_descriptors(/*_ int, int, int _*/);
    int get_dyn_statement(/* void _*/);
    void set_bind_variables(/*_ void -*/);
    void process_select_list(/*_ void _*/);
    void help(/*_ void _*/);
    #endif
    char *dml_commands[] = {"SELECT", "select", "INSERT", "insert",
    "UPDATE", "update", "DELETE", "delete"};
    EXEC SQL INCLUDE sqlda;
    EXEC SQL INCLUDE sqlca;
    EXEC SQL BEGIN DECLARE SECTION;
    char dyn_statement[1024];
    EXEC SQL VAR dyn_statement IS STRING(1024);
    EXEC SQL END DECLARE SECTION;
    EXEC ORACLE OPTION (ORACA=YES);
    EXEC ORACLE OPTION (RELEASE_CURSOR=YES);
    SQLDA *bind_dp;
    SQLDA *select_dp;
    /* Define a buffer to hold longjmp state info. */
    jmp_buf jmp_continue;
    char *db_uid="dbmuser/dbmuser@dbmdb";
    sql_context ctx;
    int err_sql;
    enum{
    SQL_SUCC=0,
    SQL_ERR,
    SQL_NOTFOUND,
    SQL_UNIQUE,
    SQL_DISCONNECT,
    SQL_NOTNULL
    int main()
    int i;
    EXEC SQL ENABLE THREADS;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    /* Connect to the database. */
    if (connect_database() < 0)
    exit(1);
    EXEC SQL CONTEXT USE :ctx;
    /* Process SQL statements. */
    for (;;)
    /* Allocate memory for the select and bind descriptors. */
    if (alloc_descriptors(MAX_ITEMS, MAX_VNAME_LEN, NAME_LEN) != 0)
    exit(1);
    (void) setjmp(jmp_continue);
    /* Get the statement. Break on "exit". */
    if (get_dyn_statement() != 0)
    break;
    EXEC SQL PREPARE S FROM :dyn_statement;
    EXEC SQL DECLARE C CURSOR FOR S;
    /* Set the bind variables for any placeholders in the
    SQL statement. */
    set_bind_variables();
    /* Open the cursor and execute the statement.
    * If the statement is not a query (SELECT), the
    * statement processing is completed after the
    * OPEN.
    EXEC SQL OPEN C USING DESCRIPTOR bind_dp;
    /* Call the function that processes the select-list.
    * If the statement is not a query, this function
    * just returns, doing nothing.
    process_select_list();
    /* Tell user how many rows processed. */
    for (i = 0; i < 8; i++)
    if (strncmp(dyn_statement, dml_commands, 6) == 0)
    printf("\n\n%d row%c processed.\n", sqlca.sqlerrd[2], sqlca.sqlerrd[2] == 1 ? '\0' : 's');
    break;
    /* Close the cursor. */
    EXEC SQL CLOSE C;
    /* When done, free the memory allocated for pointers in the bind and
    select descriptors. */
    for (i = 0; i < MAX_ITEMS; i++)
    if (bind_dp->V != (char *) 0)
    free(bind_dp->V);
    free(bind_dp->I); /* MAX_ITEMS were allocated. */
    if (select_dp->V != (char *) 0)
    free(select_dp->V);
    free(select_dp->I); /* MAX_ITEMS were allocated. */
    /* Free space used by the descriptors themselves. */
    SQLSQLDAFree(ctx, bind_dp);
    SQLSQLDAFree(ctx, select_dp);
    } /* end of for(;;) statement-processing loop */
    disconnect_database();
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    puts("\nHave a good day!\n");
    return;
    * Allocate the BIND and SELECT descriptors using sqlald().
    * Also allocate the pointers to indicator variables
    * in each descriptor. The pointers to the actual bind
    * variables and the select-list items are realloc'ed in
    * the set_bind_variables() or process_select_list()
    * routines. This routine allocates 1 byte for select_dp->V
    * and bind_dp->V, so the realloc will work correctly.
    alloc_descriptors(size, max_vname_len, max_iname_len)
    int size;
    int max_vname_len;
    int max_iname_len;
    int i;
    * The first sqlald parameter determines the maximum number of
    * array elements in each variable in the descriptor. In
    * other words, it determines the maximum number of bind
    * variables or select-list items in the SQL statement.
    * The second parameter determines the maximum length of
    * strings used to hold the names of select-list items
    * or placeholders. The maximum length of column
    * names in ORACLE is 30, but you can allocate more or less
    * as needed.
    * The third parameter determines the maximum length of
    * strings used to hold the names of any indicator
    * variables. To follow ORACLE standards, the maximum
    * length of these should be 30. But, you can allocate
    * more or less as needed.
    if ((bind_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) ==
    (SQLDA *) 0)
    fprintf(stderr,
    "Cannot allocate memory for bind descriptor.");
    return -1; /* Have to exit in this case. */
    if ((select_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) == (SQLDA *)
    0)
    fprintf(stderr,
    "Cannot allocate memory for select descriptor.");
    return -1;
    select_dp->N = MAX_ITEMS;
    /* Allocate the pointers to the indicator variables, and the
    actual data. */
    for (i = 0; i < MAX_ITEMS; i++) {
    bind_dp->I = (short *) malloc(sizeof (short));
    select_dp->I = (short *) malloc(sizeof(short));
    bind_dp->V = (char *) malloc(1);
    select_dp->V = (char *) malloc(1);
    return 0;
    int get_dyn_statement()
    char *cp, linebuf[256];
    int iter, plsql;
    for (plsql = 0, iter = 1; ;)
    if (iter == 1)
    printf("\nSQL> ");
    dyn_statement[0] = '\0';
    fgets(linebuf, sizeof linebuf, stdin);
    cp = strrchr(linebuf, '\n');
    if (cp && cp != linebuf)
    *cp = ' ';
    else if (cp == linebuf)
    continue;
    if ((strncmp(linebuf, "EXIT", 4) == 0) ||
    (strncmp(linebuf, "exit", 4) == 0))
    return -1;
    else if (linebuf[0] == '?' ||
    (strncmp(linebuf, "HELP", 4) == 0) ||
    (strncmp(linebuf, "help", 4) == 0))
    help();
    iter = 1;
    continue;
    if (strstr(linebuf, "BEGIN") ||
    (strstr(linebuf, "begin")))
    plsql = 1;
    strcat(dyn_statement, linebuf);
    if ((plsql && (cp = strrchr(dyn_statement, '/'))) ||
    (!plsql && (cp = strrchr(dyn_statement, ';'))))
    *cp = '\0';
    break;
    else
    iter++;
    printf("%3d ", iter);
    return 0;
    void set_bind_variables()
    int i, n;
    char bind_var[64];
    /* Describe any bind variables (input host variables) */
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    bind_dp->N = MAX_ITEMS; /* Initialize count of array elements. */
    EXEC SQL DESCRIBE BIND VARIABLES FOR S INTO bind_dp;
    /* If F is negative, there were more bind variables
    than originally allocated by sqlald(). */
    if (bind_dp->F < 0)
    printf ("\nToo many bind variables (%d), maximum is %d\n.",
    -bind_dp->F, MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    bind_dp->N = bind_dp->F;
    /* Get the value of each bind variable as a
    * character string.
    * C contains the length of the bind variable
    * name used in the SQL statement.
    * S contains the actual name of the bind variable
    * used in the SQL statement.
    * L will contain the length of the data value
    * entered.
    * V will contain the address of the data value
    * entered.
    * T is always set to 1 because in this sample program
    * data values for all bind variables are entered
    * as character strings.
    * ORACLE converts to the table value from CHAR.
    * I will point to the indicator value, which is
    * set to -1 when the bind variable value is "null".
    for (i = 0; i < bind_dp->F; i++)
    printf ("\nEnter value for bind variable %.*s: ",
    (int)bind_dp->C, bind_dp->S);
    fgets(bind_var, sizeof bind_var, stdin);
    /* Get length and remove the new line character. */
    n = strlen(bind_var) - 1;
    /* Set it in the descriptor. */
    bind_dp->L = n;
    /* (re-)allocate the buffer for the value.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    bind_dp->V = (char *) realloc(bind_dp->V, (bind_dp->L + 1));
    /* And copy it in. */
    strncpy(bind_dp->V, bind_var, n);
    /* Set the indicator variable's value. */
    if ((strncmp(bind_dp->V, "NULL", 4) == 0) ||
    (strncmp(bind_dp->V, "null", 4) == 0))
    *bind_dp->I = -1;
    else
    *bind_dp->I = 0;
    /* Set the bind datatype to 1 for CHAR. */
    bind_dp->T = 1;
    return;
    void process_select_list()
    int i, null_ok, precision, scale;
    if ((strncmp(dyn_statement, "SELECT", 6) != 0) &&
    (strncmp(dyn_statement, "select", 6) != 0))
    select_dp->F = 0;
    return;
    /* If the SQL statement is a SELECT, describe the
    select-list items. The DESCRIBE function returns
    their names, datatypes, lengths (including precision
    and scale), and NULL/NOT NULL statuses. */
    select_dp->N = MAX_ITEMS;
    EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;
    /* If F is negative, there were more select-list
    items than originally allocated by sqlald(). */
    if (select_dp->F < 0)
    printf ("\nToo many select-list items (%d), maximum is %d\n",
    -(select_dp->F), MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    select_dp->N = select_dp->F;
    /* Allocate storage for each select-list item.
    sqlprc() is used to extract precision and scale
    from the length (select_dp->L).
    sqlnul() is used to reset the high-order bit of
    the datatype and to check whether the column
    is NOT NULL.
    CHAR datatypes have length, but zero precision and
    scale. The length is defined at CREATE time.
    NUMBER datatypes have precision and scale only if
    defined at CREATE time. If the column
    definition was just NUMBER, the precision
    and scale are zero, and you must allocate
    the required maximum length.
    DATE datatypes return a length of 7 if the default
    format is used. This should be increased to
    9 to store the actual date character string.
    If you use the TO_CHAR function, the maximum
    length could be 75, but will probably be less
    (you can see the effects of this in SQL*Plus).
    ROWID datatype always returns a fixed length of 18 if
    coerced to CHAR.
    LONG and
    LONG RAW datatypes return a length of 0 (zero),
    so you need to set a maximum. In this example,
    it is 240 characters.
    printf ("\n");
    for (i = 0; i < select_dp->F; i++)
    char title[MAX_VNAME_LEN];
    /* Turn off high-order bit of datatype (in this example,
    it does not matter if the column is NOT NULL). */
    sqlnul ((unsigned short *)&(select_dp->T), (unsigned short
    *)&(select_dp->T), &null_ok);
    switch (select_dp->T)
    case 1 : /* CHAR datatype: no change in length
    needed, except possibly for TO_CHAR
    conversions (not handled here). */
    break;
    case 2 : /* NUMBER datatype: use sqlprc() to
    extract precision and scale. */
    sqlprc ((unsigned int *)&(select_dp->L), &precision,
    &scale);
    /* Allow for maximum size of NUMBER. */
    if (precision == 0) precision = 40;
    /* Also allow for decimal point and
    possible sign. */
    /* convert NUMBER datatype to FLOAT if scale > 0,
    INT otherwise. */
    if (scale > 0)
    select_dp->L = sizeof(float);
    else
    select_dp->L = sizeof(int);
    break;
    case 8 : /* LONG datatype */
    select_dp->L = 240;
    break;
    case 11 : /* ROWID datatype */
    case 104 : /* Universal ROWID datatype */
    select_dp->L = 18;
    break;
    case 12 : /* DATE datatype */
    select_dp->L = 9;
    break;
    case 23 : /* RAW datatype */
    break;
    case 24 : /* LONG RAW datatype */
    select_dp->L = 240;
    break;
    /* Allocate space for the select-list data values.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    if (select_dp->T != 2)
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L + 1);
    else
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L);
    /* Print column headings, right-justifying number
    column headings. */
    /* Copy to temporary buffer in case name is null-terminated */
    memset(title, ' ', MAX_VNAME_LEN);
    strncpy(title, select_dp->S, select_dp->C);
    if (select_dp->T == 2)
    if (scale > 0)
    printf ("%.*s ", select_dp->L+3, title);
    else
    printf ("%.*s ", select_dp->L, title);
    else
    printf("%-.*s ", select_dp->L, title);
    /* Coerce ALL datatypes except for LONG RAW and NUMBER to
    character. */
    if (select_dp->T != 24 && select_dp->T != 2)
    select_dp->T = 1;
    /* Coerce the datatypes of NUMBERs to float or int depending on
    the scale. */
    if (select_dp->T == 2)
    if (scale > 0)
    select_dp->T = 4; /* float */
    else
    select_dp->T = 3; /* int */
    printf ("\n\n");
    /* FETCH each row selected and print the column values. */
    EXEC SQL WHENEVER NOT FOUND GOTO end_select_loop;
    for (;;)
    EXEC SQL FETCH C USING DESCRIPTOR select_dp;
    /* Since each variable returned has been coerced to a
    character string, int, or float very little processing
    is required here. This routine just prints out the
    values on the terminal. */
    for (i = 0; i < select_dp->F; i++)
    if (*select_dp->I < 0)
    if (select_dp->T == 4)
    printf ("%-*c ",(int)select_dp->L+3, ' ');
    else
    printf ("%-*c ",(int)select_dp->L, ' ');
    else
    if (select_dp->T == 3) /* int datatype */
    printf ("%*d ", (int)select_dp->L,
    *(int *)select_dp->V);
    else if (select_dp->T == 4) /* float datatype */
    printf ("%*.2f ", (int)select_dp->L,
    *(float *)select_dp->V);
    else /* character string */
    printf ("%-*.*s ", (int)select_dp->L,
    (int)select_dp->L, select_dp->V);
    printf ("\n");
    end_select_loop:
    return;
    void help()
    puts("\n\nEnter a SQL statement or a PL/SQL block at the SQL> prompt.");
    puts("Statements can be continued over several lines, except");
    puts("within string literals.");
    puts("Terminate a SQL statement with a semicolon.");
    puts("Terminate a PL/SQL block (which can contain embedded
    semicolons)");
    puts("with a slash (/).");
    puts("Typing \"exit\" (no semicolon needed) exits the program.");
    puts("You typed \"?\" or \"help\" to get this message.\n\n");
    int connect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT ALLOCATE :ctx;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL CONNECT :db_uid;
    if(err_sql != SQL_SUCC){
    printf("err => connect database(ctx:%ld, uid:%s) failed!\n", ctx, db_uid);
    return -1;
    return 1;
    int disconnect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL COMMIT WORK RELEASE;
    EXEC SQL CONTEXT FREE:ctx;
    return 1;
    void sql_error()
    printf("err => %.*s", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
    printf("in \"%.*s...\'\n", oraca.orastxt.orastxtl, oraca.orastxt.orastxtc);
    printf("on line %d of %.*s.\n\n", oraca.oraslnr, oraca.orasfnm.orasfnml,
    oraca.orasfnm.orasfnmc);
    switch(sqlca.sqlcode) {
    case -1: /* unique constraint violated */
    err_sql = SQL_UNIQUE;
    break;
    case -1012: /* not logged on */
    case -1089:
    case -3133:
    case -1041:
    case -3114:
    case -3113:
    /* �6�Ŭ�� shutdown�ǰų� �α��� ���°� �ƴҶ� ��b�� �õ� */
    /* immediate shutdown in progress - no operations are permitted */
    /* end-of-file on communication channel */
    /* internal error. hostdef extension doesn't exist */
    err_sql = SQL_DISCONNECT;
    break;
    case -1400:
    err_sql = SQL_NOTNULL;
    break;
    default:
    err_sql = SQL_ERR;
    break;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL ROLLBACK WORK;
    void sql_not_found()
    err_sql = SQL_NOTFOUND;

    Hi Jane,
    What version of Berkeley DB XML are you using?
    What is your operating system and your hardware platform?
    For how long have been the application running?
    What is your current container size?
    What's set for EnvironmentConfig.setThreaded?
    Do you know if containers have previously not been closed correctly?
    Can you please post the entire error output?
    What's the JDK version, 1.4 or 1.5?
    Thanks,
    Bogdan

  • Lion 10.7.2 On both mac book pro and iMac, both with Lion 10.7.2, obtain repeated iCal event notifications from calendar or address book.  Cannot turn these off.  They repeat several times per session and every time computer is used.  How to diagnose this

    Lion 10.7.2 On both mac book pro and iMac, both with Lion 10.7.2, obtain repeated iCal event notifications from calendar or address book.  Cannot turn these off.  They repeat several times per session and every time computer is used.  How to diagnose this?

    First, uninstall "SuperTV" (whatever that is) according to the developer's instructions. It isn't working and it's filling the log with noise.
    If you have more than one user account, these instructions must be carried out as an administrator.
    Launch the Console application.
    Step 1
    Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left.
    Enter "BOOT_TIME" (without the quotes) in the search box. Note the timestamps of those log messages, which refer to the times when the system was booted. Now clear the search box and scroll back in the log to the last boot time when you had the problem. Post the messages logged before the boot, while the system was unresponsive or was failing to shut down. Please include the BOOT_TIME message at the end of the log extract.
    Post the log text, please, not a screenshot. If there are runs of repeated messages, post only one example of each. Don’t post many repetitions of the same message. When posting a log extract, be selective. In most cases, a few dozen lines are more than enough.
    PLEASE DO NOT INDISCRIMINATELY DUMP THOUSANDS OF LINES FROM THE LOG INTO A MESSAGE. If you do that, I will not respond.
    Important: Some private information, such as your name, may appear in the log. Edit it out by search-and-replace in a text editor before posting.
    Step 2
    Still in Console, look under System Diagnostic Reports for crash or panic logs, and post the most recent one, if any. In the interest of privacy, I suggest you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if present (it may not be.) Please don’t post shutdownStall, spin, or hang logs — they're very long and not helpful.

  • Using time() function in multithreaded application

    I am using time() function in a multithreaded application with NULL argument for getting current time.
    Some time it's observed that we get a time one minute earlier than current time (3600 seconds).
    Is there a problem in the usage of the function?
    I am using expression : currenttime = time(NULL);
    I had seen some people using following way - time(&currenttime );
    Will above two behaves differently in multithreaded environment?
    [I  am using  Sun C++ 5.5 compiler on Solaris 8]

    How do you compare actual time against the time seen by your threads? If your threads are printing the value from time(2) to stdout, it's possible that you're seeing an artifact of thread scheduling and/or output buffering.
    I really doubt that you have a concurrency problem, but anyway make sure that you include the -mt option on your compile line:
    CC -mt blahblahblah...

  • PersistenceManager Patterns for Multithreaded Applications

    Hi,
    I'm looking for a good way, how to use Kodo JDO in a multithread application
    (actually Tomcat ;). The most easy thing is perhaps, to use only one
    persistence
    manager for the entire application, i.e. for all threads. Another solution
    might be,
    to create a PersistenceManager for each HTTP request. I don't like the
    solution,
    to have one PeristenceManager per session, because I expect thousands
    concurrent
    users. What I'm concerned with is the number of data base connections in
    this
    case.
    So my question to you is, what pattern do you use in your web applications?
    When do you create and close the PersistenceManagers to free resources?
    Has anybody alreay tried different patterns and compared the performance?
    Is there something like a best practice?
    Michael

    The other nice thing about the filter is that it should be easy to
    selectivly store and retrieve the PM in a user's session if they have a
    longer running transaction that spans multiple requests.
    So far, I've simply been passing the PM to each service method, although I
    don't particularliy like that approach. I haven't had time to try anything
    different yet and it isn't TOO bad, although I have a few ideas:
    1. The hashtable method you mentioned. I see there is a "Registry" pattern
    in the "Patterns of Enterprise Application Architecture" book I'm currently
    reading, but haven't gotten to it yet. I think it is close to what you
    mentioned.
    2. Retrieve the PM through JNDI. I don't know, however, if I can set up a
    PM in JNDI the way that the CurrentTransaction JNDI lookup works with
    container managed transactions.
    "Michael" <[email protected]> wrote in message
    news:[email protected]...
    I've never used a servlet filter before but I must say that is the most
    elegant approach I've seen, thanks for sharing that. How do you pass thePM
    to the service layer? Do you store it in a hashtable with the current
    thread as a key or do you pass it in to each service method?
    Thanks,
    Michael
    "Nathan Voxland" <[email protected]> wrote in message
    news:[email protected]...
    We've created the PersistenceManager in a filter and attached it to the
    request object. That way, the persistence manager can be accessed fromthe
    Struts Action, JSP Page, and anything else we do, plus we don't have to
    worry about closing it because it is closed by the filter after
    everything
    is done (Even if an exception is thrown)
    Here is the code:
    public void doFilter(final ServletRequest request, final ServletResponse
    response, FilterChain chain) throws IOException, ServletException {
    PersistenceManager pm = getPersistenceManager();
    request.setAttribute(JDO_PERSISTENCE_MANAGER, pm);
    try {
    chain.doFilter(request, response);
    } finally {
    if (pm.currentTransaction().isActive()) {
    pm.currentTransaction().rollback();
    pm.close();
    "Michael" <[email protected]> wrote in message
    news:[email protected]...
    I currently doing exactly this: getting a persistence manager at the
    beginning of a jsp page and close it at the end of the jsp page.
    When you use <jsp:include ...>, you must be careful not to close the
    persistence manager to early. I do it like this:
    This sounds like a good approach, especially the hashtable with the
    thread
    as the key. The only issue I see is if you create the PM in the JSPpage,
    often an Action is executed before the JSP is called. This is why I
    was
    thinking of creating the PM in the struts request processor, it'salways
    called for every request.

  • Immutable Objects in multi threaded application - how does it works?

    Hi
    I have this code will work in multithreaded application.
    I know that immutable object is thread safe because its state cannot be changed. And if we have volatile reference, if is changed with e.g.
    MyImmutableObject state = MyImmutableObject.newInstance(oldState, newArgs); i.e. if a thread wants to update the state it must create new immutable object initializing it with the old state and some new state arguments) and this will be visible to all other threads.
    But the question is, if a thread2 starts long operation with the state, in the middle of which thread1 updates the state with new instance, what will happen? Thread2 will use reference to the old object state i.e. it will use inconsistent state? Or thread2 will see the change made by thread1 because the reference to state is volatile, and in this case thread1 can use in the first part of its long operation the old state and in the second part the new state, which is incorrect?
    Therad1:                                                  Thead2:
    State state = cache.get();     //t1                  
    Result result1 = DoSomethingWithState(state);     //t1    
                               State state = cache.get(); //t2
       ->longOperation1(state); //t1
                               Result result2 = DoSomethingWithState(state); //t2
                                   ->longOperation1(state); //t2
       ->longOperation2(state);//t1
    cache.update(result1);    //t1             
                                   ->longOperation2(state);//t2
                               cache.update(result2);//t2
    Result DoSomethingWithState(State state) {
       longOperation1(state);
       //Imaging Thread1 finish here and update state, when Thread2 is going to execute next method
       longOperation2(state);
    return result;
    class cache {
    private volatile State state = State.newInstance(null, null);
    cache.update(result) {
       this.state = State.newInstance(result.getState, result.getNewFactors);
    get(){
    return state;
    }

    Please don't cross post
    http://stackoverflow.com/questions/6803487/immutable-objects-in-multi-threaded-application-how-does-it-work

  • Is it supported to use Microsoft JDBC driver use in Java 7 (and 8) multithreaded applications?

    Hello everone
    is it supported to use Microsoft JDBC driver (the latest version) with Java 7 multithreaded application?
    I am planning to use standard Java 7 threads library and use separate JDBC objects per each thread, i.e. Java threads will not share any JDBC objects among them, only the thread-safe Java collections/data structures will be shared between threads (such as
    ConcurrentHashMap etc). The JDBC connections, resultsets, statements, etc will be created and dedicated per each individual thread.
    If it is supported - do you expect this design to scale-up well or am I better off using multiple but single-threaded Java/JBDC programs to access SQL Server 2012/2014 from Microsoft JDBC driver?
    Thanks
    Yuri Budilov
    Yuri Budilov Melbourne Australia

    >is it supported to use Microsoft JDBC driver (the latest version) with Java 7 multithreaded application?
    Yes, so long as:
    > Java threads will not share any JDBC objects among them,
    >do you expect this design to scale-up well or am I better off using multiple but single-threaded Java/JBDC programs >to access SQL Server 2012/2014 from Microsoft JDBC driver?
    Using threads should scale better than using processes (at least on Windows), as there is quite a bit of overhead with a process.  Each process has it's own JRE, it's own GC heap, its own threads...
    The bigger question, though, is how this scales on the SQL Server.  Your throughput may be limited by resources on your database server, and the thread's workloads may not be able to run concurrently because of locking. 
    David
    David http://blogs.msdn.com/b/dbrowne/

  • How to diagnose dead battery vs. something more serious?

    I'm in the 11th month of ownership of an MBA, purchased brand new last year.  128MB model.
    My battery, I believe, is dead but I'm not sure how to diagnose the matter.
    Here's what's lead me to this conclusion:
    MBA charger light stays off when plugged in (not dim, but off).   I've had the dim light issue as well, earlier this year, and Apple replaced the charger.  This time, however, the light stays completely off.
    Battery icon in top right corner tells me that no charger is plugged in.  The icon is in battery mode. 
    Battery charge keeps decreasing steadily in % value despite charger being plugged in, indicating that battery is continually discharging.
    My wife has an MBP, and I've used her 85W charger on my MBA with the same result... i.e charger light stays off.   I know that the MBP charger is in good health as it charges the MBP with no issues (orange light).
    I've used my MBA charger on her MBP, and it charges the MBP just fine!!! (orange light)
    I've done an SMC and NVRAM reset on the MBA, which hasn't affected the situation. 
    Since I'm on 15% charge on the MBA, I've shut it down and have booked an appointment with Apple to have it looked at.
    In the mean-time, I'm hoping to get some clues from fellow MacBook users on this forum.
    I've read somewhere that if it is indeed the battery that's faulty, then once the charger is unplugged, the MBA should turn off immediately.  This isn't the case for me... I'm able to run off battery (whatever tiny amount of charge I have left) with the charger unplugged.
    Hence, I've ruled out the charger being faulty.  I'm not so sure that the battery is faulty.  I'm thinking the issue might lie elsewhere... maybe the magsafe connector on the MBA?
    I should also mention that when I opened the lid on the MBA earlier this evening, before noticing this charging issue, the screen flickered brightly once.  The screen looked and operated normally after the flicker.  Not sure if there's a connection.  I'm beginning to think there is.
    I should also add that, even though the MBA has been a pleasure to use, the past 11 months haven't been trouble-free... which adds to the suspicion that the issue might indeed be somewhere deeper.
    A brief history of "issues":
    About a month or so into ownership... my fan, one day, decided to suddenly spin up to full RPMs and stayed at that speed for an eternity.  I'm used to the fan speed steadily going up in direct relation to the CPU temp.   However, the CPU temp this time was 35C the entire time (according to iStat Menus)... i.e. the MBA was "stone cold".  It made no sense for the fan to be on full-blast.  In addition, I had nothing running. No intensive software.  Not even Safari.  Just "Finder".   Turning the MBA off naturally caused the fan to stop.  However, the moment I powered it back on again, the fan came back on at full speed again.
    An SMC reset fixed the issue, and I was good to go.  This issue occurred again a few months later, but I solved it right away with the SMC reset.
    After another month or so I noticed, while listening to music via headphones that were plugged into the MBA, that I could hear an electric "hum" in the headphones.  Then all of a sudden the hum went away.  I discovered that the hum was present only when I physically touched the metal case of the MBA and went away as soon as I removed my hand.   I mentioned this to a Genius bar... err... genius and he seemed perplexed.  He wasn't able to offer an answer.
    I've also noticed that when the MBA is charging, and I run my finger-tips over the MBA's metal surface that I feel static.  When the charger is unplugged, I no longer feel the static.   Again the genius didn't have an answer.  He probably thought I was weird.
    I'm thinking my MBA might have "grounding" issues, but am no expert in this field.   With the latest charging issues, however, I'm leaning towards this theory again.
    Thoughts are welcome.
    Regards
    MrAir

    No clues, it is very apparent you have a hardware problem and it is not the battery. If it was the battery the computer would not be running as you say the charger is not charging the battery.
    There is a charging curcuit that has more then likely failed. You have done the correct thing, take it in and get it fixed before your warranty runs out.

  • How to diagnose flickering exported JS animations from Flash CC?

    Quick stats on my system:
    Macbook Pro Retina 2012 running OSX 10.9.3
    Flash CC 13.1.0.226
    I'm not experiencing an error so much as a lack of understanding about how to diagnose Flash CC JS export issues. Here's the backstory:
    In 2012, my company started working with an contract sprite artist. I was using the CS5.5 Creative Suite, and we were exporting normal png sequences from Flash for use in the game. After about 8 months, my cofounders and I realized that we could both reduce the load time for the game and also allow our artwork to be dynamically scalable by switching to JS exports of our art rather than the raster sprite sheets. Here's the blog post we wrote about it: http://blog.codecombat.com/hacking-our-way-to-vector-artwork-in-html5
    At the time, I didn't have Flash CC, and was reliant upon the CreateJS plugin to export the required JS files: CreateJS Developer Center | Adobe Developer Connection After another month or so, our contractor upgraded their version of Flash and we started having compatibility issues reading FLA files, so I upgraded as well. After doing some reading, I concluded that the CreateJS plugin was now incorporated into Flash CC as the HTML5 doc type, which was confirmed when I checked out the publish settings and resulting files.
    This is all a rather long winded way of saying that we have legacy artwork created with an older version of Flash but are now importing all of our artwork from JS files.
    Fast forward to today and we have two big issues:
    1) We can't figure out how to reduce the filesize of JS exports. As discussed in our blog post, vector artwork has upsides and downsides. One of the downsides we've found is that complex art that uses a lot of shapes ends up being substantially larger (in terms of filesize) than the appearance might otherwise suggest. Raster exports skirt this because a pixel is a pixel, but vector exports scale with the complexity of the source FLA. I'm not a Flash expert, and when we get files that are particularly complex, Flash either runs out of memory exporting them to JS files or we get files that are far too large to reasonably use. To be clear, the "out of memory" error isn't a problem because even if Flash finished the export, the resulting files would be too large for us to use (plus, I've done some digging and found a tutorial for correcting the out of memory error). Our artist is not familiar with the intricacies of the JS Flash exporter, so when we get a file that's too big or breaks the export, neither of us can really figure out a way to correct the problem. We have three questions in particular:
         a) Where can you view shape data that Flash is going to write to the JS files?
         b) Is there any way to edit said shape data inside the Flash CC interface?
         c) Is there any way to optimize shape data in Flash? For instance, in Photoshop, you can flatten images and export a psd with 500 layers as a single JPEG, is there any way to do something similar to shape data in Flash?
    2) Exports frequently break in weird ways. Many of the sprites that we created a year ago haven't needed to be re-imported into our game engine for some time. But every once in a while, I need to go back and fix, improve, or tweak an existing sprite, and then I run smack into the issue of reconciling files that were created without thought to JS exports with our current system. Just last week I was running into this issue in a big way and I made a screencast for our artist (since we work remotely) that I hoped might give him a better idea of the problem: Flash Errors - Treasure Chest, Flippable Tile - YouTube
    The two files mentioned in that screencast are both old (treasure chest) and new (flippable land tile). We have a few questions:
         a) Why are the treasure chest frames "flickering" in the html5 preview? The problem doesn't appear inside Flash and is inconsistent between files. There are two FLA files: one in which the treasure chest is empty, and one in which it's full. The empty animation doesn't throw any errors, either when converting to the HTML5 doc type or on export, but the resulting animation flickers. The full treasure, on the other hand gives me 21 lines of these errors when I do the conversion (not when I export): "Blend Modes(Layer) is not supported in HTML5 Canvas document, and has been converted to Normal in an instance of Movieclip <Path>." The result in both cases is the same: the animations flicker, and neither our artist nor us can figure out why, or for that matter, even begin to troubleshoot it. This SO issue seems to describe the problem, but was never resolved, and I can't find anything else that seems to address it: CreateJS Publish of Flash Project Flickers - Stack Overflow
    I've uploaded the files involved to a public dropbox folder which I think you'll be able to access (Dropbox seems to be having some problems at the moment): Dropbox - flash_debugging
    Since my questions are fairly involved, and my goal is to gain a better understanding of the UI, not simply resolve an error, I'd be happy to pay for someone's expertise/time in getting me up to speed. You can get in touch with me at george [at] codecombat.com

    Hi George,
    I have taken a look at the files full_treasure_chest.fla and flippable_land.fla that you have shared via drop box and found that they both uses blank keyframe(s) followed by Keyframe(s). This was an issue and has been addressed in the latest release Flash CC 2014 (released on 18 June, 2014). Can you please install the latest build 14.0.0.110 and try this out?
    Thanks!
    Mohan

  • I have switched offices and computer. may I still access my old tunes? next, I get an error when trying to download Itunes to my new compuet: c:\DocumentsandSettings\aabugattas\desktop\itunessetup.exe is not a valid Win32 application  How can i download i

    I have switched offices and computer. may I still access my old tunes? next, I get an error when trying to download Itunes to my new compuet: c:\DocumentsandSettings\aabugattas\desktop\itunessetup.exe is not a valid Win32 application  How can i download it?

    In the course of your troubleshooting to date have you worked through the following document?
    iTunes: Windows reports that "iTunesSetup.exe is not a valid Win32 application"

  • A Java application how to pass Microsoft OEM Ready program?

    Hello,
    I have a Java application that needs to pass OEM Ready program, but it fails on AppVerifier item. The error messages are:
    "Freeing memory block inside current thread's stack address range."
    "First chance access violation for current stack trace."
    These errors are occurred by JVM. Anybody understands a Java application how to pass AppVerifier? Thanks in
    advance.
    p.s. The Java application is only a simple "Hello World" program.
    p.s. I also test many popular Java applications (such as JBuilder/NetBeans), they
    also cannot pass AppVerifier.
    p.s. The OEM Ready Program web site: http://msdn.microsoft.com/en-us/windowsvista/cc315067.aspx

    One small update. These errors are reported by AppVerifier tool. But the origin of the errors seems to be coming from JNI Calls. Basically AppVerifier is a runtime verification tool and helps in monitoring an application's interaction with OS, the registry, the file system,heap, handles, locks, and more and reports the errors found.
    And when I check my application ( which interacts with few .jar files using JNI calls ) with AppVerifier, it is reporting the errors, upon debugging I found the source of the errors to be the JNI calls. Any idea about the reasons and fix for these errors.
    I thank you in advance.

Maybe you are looking for

  • Application for receiving application not working..

    Hi..experts. i m new to j2me programming. plese help me. I got an application for receiving SMS from net. i nstalled it on nokia N73. but it's not working. this is the code of that app... package receivedemo.sms; import javax.microedition.lcdui.*; im

  • How to create line in smart form

    dear all,         i hv to create lines in smartform. BOX XPOS '0' MM YPOS '6' MM HEIGHT '0' MM WIDTH '190' MM FRAME 1 PT by using above statement i can create line in SAPSCRIPT. is there any similar statement in smartform to create lines if So plz se

  • The message no vl049 is changed  from warnning prompt   to error  prompt.

    hi : i want to change the message type from warning  prompt to error prompt.please provied  me with means . best regards.

  • Creating Repository Services advice!

    Hi All I am currently looking into creating and developing Repository Services and I am have a little difficulty understanding basic code and structure. I have managed to alter examples which various people have helped me with but that is now not eno

  • I am unable to access my ipod

    please tell me how to access my ipod and i want to