Executors.newSingleThreadScheduledExecutor() creating multiple threads?

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

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

Similar Messages

  • Creating multiple Threads in applets

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

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

  • How to handle multiple threads to read one line from a file each time?

    Dear Sir or Madam,
    I'm new to multiple threads java programming. What I want to do is as following:
    1. I'm writing a program to read one line of text from a very large file, and then do some process on this one line of text, then read the next line of text from this file, then process on this line of text, ...... When reach the end of the file, close the file.
    This is a single thread scenario.
    2. To fullly untilized computer resource, I want to create multiple threads to process this large file.
    One thing is very important is that each line of text in the large file has to be read sequentially. This means that the first line of text in the large file is read first, then the second line, then the third line ......
    My question is that if I create multiple threads to process the same file, how can I make sure that different threads will read the line of text from the same file sequentially?
    I don't have enough experience on java multiple threads programming, so it will be very appreaciated if you can help me on this as soon as you are available.
    Thanks and regards,
    Steven Wu

    A better solutoin would be to have a single thread that reads each line an puts it into a queue, and then multiple threads reading from the queue to process these lines.
    This will only be effective if the amount of processing to be done on each line is very large compared to how long it takes to read the line, or if you have more than one CPU on your machine.

  • How can I force TestStand to create multiple instance of an activex server instead of share the same reference?

    Hi, All:
         I am trying to migrate a application coded by VC++ to TestStand+CVI. This application opens multiple serial com ports and send commands to test targets, and get responses from these targets. The VC++ application creates multiple thread, and every thread create an activeX server instance which is responsible for opening serial port,sending test commands ,and getting response. It works fine as every thread has itsown activeX instance, so data and commands can be handled in the right serial port successfully.
         Yet when I works on TestStand, I got problems. I choose parallel model as the process model. I create a activeX object reference with AxtiveX/COM Adapter, and store the reference in a sequence local varialbe. If there is only 1 testsocket, It is OK. But if there are multiple test sockets, and communication between the application and test targets will be directly to the last test target. I try to popup a message within a execution to indicate the value of the activeX object reference, and all of them are identical. But this is not the behavior I want.
        So, is it possible to force TestStand to create independent instances of an activeX server? How can I make it work?
    Thanks

    Thanks for your comment, Dan.
          Yet I do get problems as none of us know how to program an activeX server so that it can be forced to be a single-instance or multiple-instance.
    As I mentioned earlier, there is existing application which is written by VC++ can create multiple instances of this activeX server, all I have to do is to create multiple threads, and initiate an instance of this server to contrl multiple test targets.
         My colleague said he creates the server with VC++ ATL, and cofigure it to be dual-interface and STA. And in the VC++ application side(client side), I use smart-pointer in threads to create an instance of the server:
     IMySerialServer pIMySerialServer;
      HRESULT hr = pIMySerialServer.CreateInstance("UUTCmd.MySerialServer");
      if(FAILED(hr))
       AfxMessageBox("Fail to create instance.");
    And then I got multple instances of the activeX server. Every thread can have itsown com port, can send/receive commands indepently. I have no idea how can I make it work on TestStand. Would you show me some reference documents or sample codes?
    Thank you
    Cipher

  • Starting Multiple Threads

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

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

  • Jdbc and multiple thread

    hi, i have an application that creates multiple thread..each thread (querythread) is accessing a webservice(querydb) that retrieves data from different databases. This webservice supposed to create a jdbc connection each time it is invoke by the querythread. The problem is i get an error that a particular table does not exist in the server..This is cause by the confusion in my program..
    The table is access in the wrong server..e.g.(cdsisis.TblHoldings does not exist) this is because thread is confuse and using a different connection..when i tried to use the querydb webservice directly per database it is ok. but when i try to make multiple thread to invoke querydb accessing different database it has this error: cdsisis.TblHoldings does not exist
    cdsisis is a database server..and tblHoldings is a table in another database named silms. i think the thread tends to share resources.
    should it be that thread supposed to be independent with each other? how come this is happening?

    hi, i have an application that creates multiple
    thread..each thread (querythread) is accessing a
    webservice(querydb) that retrieves data from
    different databases. This webservice supposed to
    create a jdbc connection each time it is invoke by
    the querythread. The problem is i get an error that a
    particular table does not exist in the server..This
    is cause by the confusion in my program..
    The table is access in the wrong
    server..e.g.(cdsisis.TblHoldings does not exist) this
    is because thread is confuse and using a different
    connection..when i tried to use the querydb
    webservice directly per database it is ok. but when i
    try to make multiple thread to invoke querydb
    accessing different database it has this error:
    cdsisis.TblHoldings does not exist
    cdsisis is a database server..and tblHoldings is a
    table in another database named silms. i think the
    thread tends to share resources.
    should it be that thread supposed to be independent
    with each other? how come this is happening?I think you should lock your thread while trying to make request or making your connection. When you lock your thread, the currently used variable can not be accessed by another thread. Actually I know you are creating different treads and create different instances of connection. But some how some methods are not thread safe, it means they are static or use static variables. So they change from another thread, while you are trying to access it.
    If lock does not work try this,
    synchronized(this){
    //do your stuff
    }

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

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

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

  • I group messaged from my ipad and this has screwed up the way my messages are reveived by my friends (it creates new threads in their phones with my email in place of my contact name) I've stopped messaging from my ipad but the problem remains. Any help?

    I have an iPhone 4S and use the group texting feature ALL THE TIME. I recently updated my iPad to the latest software and made the colossal mistake of continuing my group messaging from my iPad while connected to wifi. Doing this has successfully screwed but every group text thread I am in, to the point where its very hard for those involved in the thread to keep up. When I initially messaged those I was already engaged in text threads with it created a new thread in their phones replacing my name in their phones with my email. At first this was not a big deal but ever since then the people I am messaging have become increasingly frustrated with how my messages come through. If I am messaged in a group text and respond to it, sometimes when I respond it will create an entirely different thread in my recipients phones. So at that point they have to switch threads in order to read what I wrote. The new thread that my phone creates will send the message under my email not my name (related to the contact they have me saved as in their phones). The worst part about it is that there seems to be no rhyme or reason to why or when my phone will send the message as normal or under my email like it did with my iPad. I haven’t messaged from my iPad since these problems immediately began a month ago but the issues still continue. I have tried everything to get this to stop, I’ve turned off my wifi, I’ve had my friends delete the threads that my messages create in their phones. I’ve had them delete my email in their contact lists and nothing has worked. Can you help me? Any info you could provide would be greatly appreciated.
    Note: My phone message no different whatsoever. All the threads have remained the same. The issue is what it is doing to the people that I am messaging.
        Best Regards
             Rick Mulhern
    Message was edited by: Rickapplehelp19

    I have this identical problem.  For a while my group texts didnt show up on my ipad.  Then one day they did, maybe everyone in the group started using the same os version or something.  Ever since my first reply to the group there have been complaints of multiple threads.  I can not find a pattern for when my group text's decide they want to create a new thread. (it doesnt happen every time)  Everyone in the group has deleted the thread, we've all toggled imessage on/off etc.  There still hasn't been a solution.
    Any help would be appreciated.
    Thanks

  • Using Select all to create multiple lines in a sales order

    Hello SAP experts,
    In our business practice users create multiple line sales orders with reference to contracts and use the copy paste method and then assign each line to the contract manually.
    After a few years of this practice i found a new way to create multiple lines but it doesn't quite work correctly. When you have created the first line of an order if you click on the select all button the system will ask you how many lines do you want to copy. I don't know if this is standard SAP but 3 things don't happen when we use this 1) The schedule line information is blank 2) conditions do not copy from the contract even though the contract has been referenced. 3) Since there is no schedule line information the order fails when saving and we get a update terminated message.
    I am having problems finding any documentation around this function so any help with this would be greatly appreciated.
    error when updating is
    Transaction..   VA01
    Update key...   4D358878A8B601AAE10080000A2C4982
    Generated....   28.01.2011, 13:47:23
    Completed....   28.01.2011, 13:47:23
    Error Info...   00 671: ABAP/4 processor: GETWA_NOT_ASSIGNED

    GETWA_NOT_ASSIGNED
    Many threads are there on this error message and you would come to know if you google with this text.  Check couple of threads where  the same topic was discussed
    [Re: GETWA_NOT_ASSIGNED|Re: GETWA_NOT_ASSIGNED;
    [Re: GETWA_NOT_ASSIGNED ABAP Dump|GETWA_NOT_ASSIGNED ABAP Dump;
    Also there are some 20 OSS notes on this error message and you can have a look at the following notes:-
    1)   Note 913679 - VA01: Short Dump GETWA_NOT_ASSIGNED on click of quantity.
    2)   Note 591955 - ABAP runtime error GETWA_NOT_ASSIGNED
    3)   Note 870670 - SD_SALES_DOCU_MAINTAIN_DIALOG termination with GETWA_NOT_***
    4)   Note 141314 - VA02: Dump with 'GETWA_NOT_ASSIGNED'
    thanks
    G. Lakshmipathi

  • How do i use multiple threads( very much real time), using JavaFX?

    I'm creating an application, using JavaFX because one can create awesome GUI using JavaFX. I need to know how to create real time multiple threads using javafx.
    JavaFX doesn't support creation of multiple threads, but i think there is another way of doing it. I need it work in real time as my application works with an hardware (wacom intous 3 tablet), and i need mutiple threads to get all the parameters from the stylus of the tablet simultaneously...
    any code which will help me out or explaination on how to go about this is appreciated...
    Help required quickly...

    See example at
    [http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/|http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/]

  • How i can create multiple users at a time (User Administration) in EP

    Hi
    I need to create multiple users at a time. How can i do that through User Administration in EP.
    Please also tell me about import option in User Administration

    Hi,
    1.  First of all create a master user based on which you can create multiple users.
    2.  when you are done with it  export (by selecting the option at user creation) it.
    3.  you can see some text in a window copy it create  a txt file with it, and add as many users as you want
         by cpoy pasting the text multiple times and making necessary change as per the names etc...
    4. save the txt file.
    5. goto import option you were talking about and import the text file and update it.
    6. As it gets updated you are done with the creation of multiples users.
    If you  get stuck somewhere  feel free to  let me know.
    if  this answer satisfies your need, award points and close the thread.
    Edited by: ali alia on Feb 10, 2009 6:21 AM

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

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

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

  • Multiple threads calling the same stored proc with different parameters

    Hi,
    I have a stored procedure which will be called by 8 threads. Every time it takes in a different parameter.
    Actual execution time for this proc (irrespective of the parameter) is around 2 seconds. But when I call the 8 threads, I see that the total time taken (END TO END) is around 16 seconds. Threads do acquire a read lock right? Is there a way i can get over this issue?
    Please let me know.

    Sybase IQ is the database. I am using a thread pool. The time taken to execute this procedure without threads is about 2 seconds. It takes 16 seconds when I start using threads.
    I do something like this :
    ///////////////////////// databaseThreadPool.java
    * example of a fixed-size thread pool using the
    * executors introduced in Java 5
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class databaseThreadPool
    public static void main(String[] args)
    * create a thread pool with four threads
    ExecutorService execSvc = Executors.newFixedThreadPool( 8);
    * place six tasks in the work queue for the thread pool
    for( int i = 0; i < 6; i++ )
    execSvc.execute( new CountDown() );
         long a =System.currentTimeMillis();
    execSvc.execute( new databaseThread("00055","YTD","GROSS") );
    execSvc.execute( new databaseThread("00055","YTD","NET") );
    execSvc.execute( new databaseThread("00055","YTM","GROSS") );
    execSvc.execute( new databaseThread("00055","YTM","NET") );
    execSvc.execute( new databaseThread("00055","LY","GROSS") );
    execSvc.execute( new databaseThread("00055","LY","NET") );
    execSvc.execute( new databaseThread("00055","LLY","GROSS") );
    execSvc.execute( new databaseThread("00055","LLY","NET") );
         long b =System.currentTimeMillis();
         try{
         while(databaseThread.done!=8)
              Thread.sleep(1000);
         catch(Exception ex){}
    execSvc.shutdown();
    System.out.println("END TO END TIME TAKEN : "+(b-a));
    /////////////////////////////////////////////////////////// databaseThread.java
    import java.io.PrintWriter;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.io.PrintWriter;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.io.IOException;
    public class databaseThread implements Runnable
    protected int count = 8;
    * the following counter is incremented once
    * each time the class is instantiated, giving each
    * instance a unique number, which is printed in run()
    private static int taskCount = 0;
    private final int id = taskCount++;
    private String gpNum;
    private String time;
    private String domain;
    public static int i=0;
    public static int done=0;
    PrintWriter out = null;
    Connection connection = null;
    Statement statement;
    ResultSet rs;
    ResultSetMetaData rsmd;
         CallableStatement cStmt = null;
    public databaseThread(String gpNum, String time, String domain) {
    this.gpNum=gpNum;
    this.time=time;
    this.domain=domain;
    * print the id and the iteration count to the console, then
    * yield to another thread.
    public void run()
         try
         Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
         connection = DriverManager.getConnection("jdbc:sybase:Tds:XXXXXXXXXXX:XXXXXXX", "cp_dbo","cp_dbo");
         statement = connection.createStatement();
              cStmt=connection.prepareCall("{call XXXXXX ?,?,?)}");
              cStmt.setString(1,gpNum);
              cStmt.setString(2, time);
              cStmt.setString(3,domain);
              long a =System.currentTimeMillis();
              rs=cStmt.executeQuery();
              long b=System.currentTimeMillis();
              System.out.println(id+" Time taken by to execute Query : "+(b-a));
         //rsmd=rs.getMetaData();
              while(rs.next())
              Thread.yield();
         catch (ClassNotFoundException e) {
              System.out.println("Driver Error" );
              e.printStackTrace();
              } catch (SQLException e) {
              System.out.println("SQLException: " + e.getMessage());
    }

  • Can multiple threads write to the database?

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

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

  • Berkeley DB Java Edition - multiple threads accessing database

    Hi,
    I would like to access (read & write) a Berkeley DB from multiple threads (all same process/jvm).
    Should I use a single com.sleepycat.je.Database object for all threads, or should I create an instance for each?
    Or is there any other way of doing it?
    Thanks

    The Database object may be used by multiple threads, so you can use a single instance or multiple ones, as best suits you. From http://docs.oracle.com/cd/E17277_02/html/java/com/sleepycat/je/Database.html,
    Database handles are free-threaded and may be used concurrently by multiple threads. 'If you read through the javadoc, you'll find other notes on using classes from multiple threads.
    Regards,
    Linda

Maybe you are looking for

  • How do I create a form using data collected from a previously completed form?

    I need my users to fill in an initial registration form with a range of details. Six months or so later I need to ask the users to confirm the details and also fill in new information. Is there a way I can have the second form be automatically popula

  • SQLLOADER issues with Network Drive

    Hi , I am running Oracle 10g in my PC ( Windows XP Professional ) in D Drive. I have created Oracle Directory and mapped to Network Drive Z: I have created external table successfully with this Directory. When i run select statement, i am getting the

  • NI HyperTrend Control raises the CPU usage of NI Citadel DB and freezes it.

    When a VI uses NI HyperTrend Control to fetch data from NI Citadel DB, the CPU usage of citadel is raised up to 10% and stops working. I don't know what "stops working" means since my coworker told me so. How can the control be prevented from freezin

  • Parsing errors with CDATA tags using oracle xml parser v2

    I'm using the oracle.xml.parser.v2 parser to combine a generated xml document from a database with a static xsl file to produce html. Within the xml document, there are fairly large CDATA sections (500 lines) which happen to contain javaScript. Occas

  • "iPod Service Failed to Start" message when upgrading iTunes

    When upgrading iTunes from Version 7 to the newest version, I got an error message stating "Service, 'iPod Service' failed to start. Verify that you have sufficient priviledges to start system services." So I canceled the download and rolled back to