Passing Connection to Another Thread

I have an email blasting POJO that is used to notify interested members when new content is posted on our site. This may involve sending a couple hundred emails (as I don't want one email with several hundred receipients) so I have it threaded. It pulls email address information from the user database, so I pass it the a connection from our pool.
As this thread now has this connection, I don't close it from the originating class that created it, as it may still be in use (correct?) so instead I have the threaded mailer close it.
Does this sound clean or is there a better way to do this?

But i am not sure how do u read the values from the
resultSet return from the super class as it will
close the connection object. Well once the connection
object is closed the resultset is also closed isnt
it??
Please enlighten us how did you do it in your
project. Ofcourse it would.
**sigh** dint i mention it was pseudo code ?
You dont tamper with ResultSets outside the DAO, period. You do not
pass data back to the caller (be that your sub DAO classes or your front
end handlers/servlets/jsps) .
To the super class DAOManager, a model class and a Map is passed.
The DAOManager class populates the specified model object from a
resultset. The map contains the mapping from database column
names to the properties in the model object. The key of the
modelObjectMap is the database column name and the value is the
name of the property in the model object. Properties in the model
object are mapped according to the mapping suggested by JDBC 2.1
API.
Thus the code would be
public List executeQuery(String sqlString, List bindValues,
            Class a_class, Map dbModelMap){
            Connection dbConnection = getConnection();
            String sql = prepareSql(sqlString, bindValues); //private method
//that binds the values to the raw sql string and creates a prepared
//statement
             ResultSet results = executeQuery(); //private method again that
//executes the prepared staement object.
             return getObjectResults(results, a_class, dbModelMap);
              //close result sets, connections etc in finally
private List getObjectResults (results, a_class, dbModelMap){
             //for each result set iteration{
                    //create an instance of a_class
                    //lookup the map - for each column, find the corresponding
//attribute in the class, using reflection, call the setter methods for
//the column value
                    //add the instance to a list
             //return list
}I dint post this initially because I have seen enough of linxpda's posts
to know that he would have grasped the essentials quickly enough.
I dint account for the others who may happen to read this post - I stand
corrected.
cheers,
ram.

Similar Messages

  • Closing socket connection from 2nd thread

    I did some research on different operating systems to find a unique solution how to timeout a blocking recv call in one thread.
    Closing the connection from another thread helps but I found that there are two different methods how to close the connection:
    - either just calling close with the correct linger options
    - call shutdown first and then close
    Unfortunately most platforms work fine with only one of these methods and fail more or less severe with the other method.
    While I think to fully understand the behavior of Windows and Linux, Solaris is still a big question mark for me.
    I have some machines (running Solaris 8, 7 and 2.6) which work well with just closing and crash the system when using shutdown (while having bad luck in the timing of the other peer). And I have another 2.6 machine that behaves the other way around.
    I created a detailed description about the whole problem and my findings in a PDF if you are interested: http://www.webwasher.com/download/notes/timeoutblockingsocketcall.pdf
    Is anybody able to explain how the Solaris implementation works here?
    And does anybody know why I see the differences with the two 2.6 boxes? (I changed patch level and exchanged clib without success.
    Martin

    I have a main program which creates a thread.Why not create a thread once the object has been read.
    The thread would take some time to process this
    object before it accepts another object to be passed
    in from the main program.Threads are used for concurrent execution. If you don't want concurrent execution, don't use additional threads. Have the main program do the reading and execution and then it cannot read another object until it has finished executing the previous one.
    >
    However, I realise that my main program:
    s = new Socket("localhost", 2001);
    will produce a socket connection
    socket connection even if the thread is still
    processing the object. Why is this possible?This is what threads do. It is call multi-threading.
    Initially I thought the thread would lock the socketIt will lock the sockect when you lock it with synchronized. Howver you are creating a new socket each time so even this would not do what you suggest.
    and my main program would not be able to get a socket
    connection until my thread releases the socket.Everytime you call new Socket() it creates a NEW socket. You can open as many socket as the server can handle. (10000+)
    Code in my thread to accept a socket connection:
    server = new ServerSocket(2001);
    ois = new ObjectInputStream(server.accept().getInputStream());I would suggest putting the Socket created by server.accept() into a variable. Otherwise you will not be able to reply to the request, nor will you be able to close() the connection.
    How can I workaround this issue. Hope somebody can help. Thanks.You don't need a workaround, you need to fix the logic of your application.

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • Catching an exception thrown from another thread

    I have a SocketServer that creates new threads to handle incoming clients. If one of the threads throw a SQLException is it possible to catch that exception in the SocketServer that created that thread.
    I tried implementing this code and I cannot get the server to catch an exception thrown in the thread. Are my assumptions correct?
    I was reading something about Thread Groups and implementing an uncoughtException() method, but this looked like overkill.
    Thanks for your time!
    Some Example code would be the following where the ClientThread will do a database query which could cause an SQLException. I'd like to catch that exception in my Socket Server
          try
                 new ClientThread( socketServer.accept() , host, connection ).start();
          catch( SQLException e )
                 System.out.println( "DataSource Connection Problem" );
                  e.printStackTrace();
          }

    hehe, why?
    The server's job is to listen for an incoming message from a client and pass it off to a thread to handle the client. Otherwise the server will have to block on that incoming port untill it has finished handling the client and usually there are many incoming clients continuously.
    The reason I would want to catch an exception in the server based on the SQLException thrown in the thread is because the SQLException is usually going to be due to the fact the datasource connection has become unavalable, or needs to be refreshed. This datasource connection is a private variable stored in the socket server. The SocketServer now needs to know that it has to refresh that datasource connection. I would normally try to use somesort of flag to set the variable but to throw another wrench into my dilemma, the SocketServer is actually its own thread. So I can't make any of these variables static, which means I can't have the thread call a method on teh socket server to change the status flag. :)
    I guess I need implement some sort of Listener that the thread can notify when a datasource connection goes down?
    Thanks for the help so far, I figured java would not want one thread to catch another thread's exceptions, but I just wanted to make sure.

  • Javascript: to pass values to another page

    hi all,
    i hav an interactive report. if i clik on a particular row, that row values must be passed to an another page (via javascript)
    i found this forum https://forums.oracle.com/thread/2467579 in which they hav used it for sending mail.
    but i wanted to pass those values to another page throug javascript bz, i hav installed a plugin nd wrking from it under right clik.
    ma  javascript function  is,
    function func(action,el, pos)
       window.location ="http://apex.oracle.com/pls/apex/f?p=71510:2:&SESSION.:::2:P2_X,P2_X2:'+ $(el).children('td[headers="EMPNO"]').text() +  ',' + $(el).children('td[headers="ENAME"]').text()";
    here i hav redirected it to the 2nd page and in the 2nd page i hav used 2 items to get these values.
    $(el).children('td[headers="EMPNO"]').text() +        ------->  this is to fetch the empno of that particular row and similarly for the name.
    but if i click on the right clik button , no action is happening... 
    but its working fine, if i use the function as,
    function func(action,el, pos)
       window.location ="http://apex.oracle.com/pls/apex/f?p=71510:2:&SESSION.";
    so somewhere is going wrong in passing the values in URL i suppose....
    and i hav used al d above things in
    http://apex.oracle.com/pls/apex/f?p=71510:1 (username: test / paswrd: pex14gm)
    pls help me out.....
    thanks in advance

    Try like this.
    function func(action,el, pos){
        var empNum = $(el).children('td[headers="EMPNO"]').text();
        var eName  = $(el).children('td[headers="ENAME"]').text();
        window.location ='http://apex.oracle.com/pls/apex/f?p=71510:2:&SESSION.:::2:P2_X,P2_X2:'+empNum+','+eName;
    It looks simple and neat.
    If you still didn't get post me workspace details.

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • Passing Connection object from web tier to ejb tier

    I am having a multi threaded application where i am creating multiple threads and doing ejb lookup in each thread and there in ejb it is creating a database connection.
    But i wish to pass only a single connection so that total no of free connections will be more.
    i am creating a connection in my web tier and passing it in each thread and then to ejb tier. But i am getting a class cast exception
    java.lang.ClassCastException: com.sun.gjc.spi.ConnectionHolder
         at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.write(DynamicMethodMarshallerImpl.java:338)
         at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.writeArguments(DynamicMethodMarshallerImpl.java:407)
         at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:157)
         at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:119)
         at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:197)
    Please give some insight where i am doing wrong also suggest me a better way to do it.
    TIA
    ~seshu

    Hi Krishendu,
    I think this is a bug in 9.0.2 that is fixed in 9.0.3/9.0.4.
    Can you please contact Oracle support and see whether they can provide a patch for this problem.
    regards
    Debu

  • Lappy wireless with iwl4965 issues .. yes another thread

    Another thread in the tonne I searched up and completely failed to find a solution to my problem in. Wish I could remember the ancient email I signed up for the forums ages ago with too =[
    Anyways... Problem: All activity drops in mere seconds upon first trying to connect to any site...
    I have the driver installed fine, along with wicd which has control of my wlan0 like it should, the scan of SSIDs turns up fine, I can connect to my network fine too.
    I can get an IP addy just fine, I can ping external IPs endlessly.
    I can resolve IPs it seems, I tried pacman with wget to make sure my IPs were being resolved properly, it always connects and gets the first few tarballs, then on one of them the speed (as reported by wget) drops from full speed to 0 over a few seconds, and it never picks up again, and fails to retrieve any more files.
    http sites are the same, it connects for a second, then is endlessly waiting.
    Would love to get this working, and I should point out I have no problems at all with my ethernet connection.
    Any ideas guys?

    i use the same driver as you guys for my 
    Intel Corporation Wireless WiFi Link 5100
    and "network manager" and have no problem whatsoever.
    To get my wifi working i had to copy the
    iwlwifi-4965-2.ucode
    file into "/lib/firmware".
    Try doing the same, might work

  • Pass messages between main thread and FX application thread

    I'm launching an FX Application thread from a Main thread using Application.launch [outlined here: {thread:id=2530636}]
    I'm trying to have the Aplication thread return information to the Main thread, but Application.launch returns void. Is there an easy way to communicate between the Main thread and the Application thread?
    So far I have googled and found:
    - MOM (Message Orientated Middleware)
    - Sockets
    Any thoughts/ideas/examples are appreciated - especially examples ;) - right now I am looking at using Sockets to show/hide the application and for passing data.
    What is the preferred method? Are there others which I have not found (gasp) via Google?
    Dave.
    Edited by: cr0ck3t on 30-Apr-2013 21:04
    Edited by: cr0ck3t on 30-Apr-2013 21:05

    Is there an easy way to get a reference to these objects from both the Main thread and the FX Application thread - called via Application.launch() from the Main thread? Or do I have to use Sockets or MOM?Not much to do with concurrent programming is what I would call easy. It seems easy - but it's not.
    You can kind of do what you are describing using Java concurrency constructs without using sockets or some Message Oriented Middleware (MOM) package.
    With the Java concurrency stuff you are really implementing your own form or lightweight MOM.
    If you have quite a complex application with lots of messages going back and forth then some kind of MOM package such as camel or ActiveMQ (http://camel.apache.org) is useful.
    You can find a sample of various thread interactions with JavaFX here:
    https://gist.github.com/jewelsea/5500981 "Simulation of dragons eating dwarves using multiple threads"
    Linked code is just demo-ware to try out different concurrency facilities and not necessarily a recommended strategy.
    If your curious, you could take a look at it and try to work out what it is, what it does and how it does it.
    The main pattern followed is that from a blocking queue:
    http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
    Note that once you call launch from the main thread, no subsequent statements in the main method will be run until the JavaFX application shuts down. So you can't really launch from the main thread and communicate with a JavaFX app from the main thread. Instead you need to spawn another thread (or set of threads) for communication with the JavaFX app.
    But really, in most cases, the best solution with concurrency is not to deal with it at all (or at least as little as possible). Write everything in JavaFX, use the JavaFX animation framework for timing related stuff and use the JavaFX concurrency utilities for times when you really need multiple thread interaction.
    http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
    To get further help, you might be better off describing exactly (i.e. really specific) what you are trying to do in a new question, perhaps with a sample solution in an sscce http://sscce.org

  • Killing an exec'ed process from another thread

    Hi all,
    I written an application that executes some external OS - processes. There is a dispatcher thread, that starts the execution threads for some jobs. Every execution thread creates a Processes by calling runtime.exec(), adds this object to a TreeMap ( member of the dispatcher ), creates two threads for reading the output of the process ( sdtout & stderr ) and calls p.waitFor(). From this moment this thread is blocked. After the process is done, the results will be processed by this thread etc. Now I want to go ahead and let the application user kill the process. For them I let the dispatcher - thread, that has also a reference to the executed process to call destroy of it if necessary during the execution thread is blocked by waitFor() and two output threads are reading stdout & stderr. The problem is however that destroy() - call from another thread doesn't kill the subprocess. The subprocess is running until it's done or terminated from out of jvm. Have you an idea or example?
    Thanks a lot & regards
    Alex

    >
    I know you have been discussing your problem is that
    you can't kill a "sleep" process. But just to be
    sure, I tested your description by one thread exec-ing
    a "not-sleep" program, and then another thread had no
    trouble killing it.
    I took your code and wrote a program around it such
    that
    Thread1 :
    - creates a Job (but not a "sleep" job); creates a
    JobMap ; puts Job in JobMap
    - starts Thread2 (passing it JobMap)
    - sleeps 15 seconds
    - calls Job.kill() (your method)
    Thread2 :
    - gets Job from JobMap
    - calls Job.execute() (your method)
    It's quick and dirty and sloppy, but it works. The
    result is when the kill takes place, the execute
    method (Thread2) wakes from its waitFor, and gets
    exitValue() = 1 for the Process.
    so,
    In order to kill the sleep process, which (according
    to BIJ) is not the Process that you have from exec
    call, maybe the only way to kill it is to get its PID
    an exec a "kill -9" on it, same as you said you had to
    do from the commandline. I don't know if you can get
    the PID, maybe you can get the exec-ed process to spit
    it onto stdout or stderr?
    (I am on win, not *nix, right now, so I am just
    throwing out a suggestion before bowing out of this
    discussion.)
    /MelHi Mel,
    yes, it should work right on windows because you created probably the shell by cmd /c or something like this. If you kill the cmd - process, everithing executed by the interpretter will be killed too. My application is running on Windows and unix. On unix I have to execute the process from a shell ( in my case it is the born shell ). The problem is however, that the born shell has another behaviour as cmd and doesn't die. Do you have an idea how to get the pid of the process started by sh without command line? To kill the processes from the command line is exactly what my customers do now. But they want to get "a better service" ...:-)
    Regards
    Alex

  • To kill a connection (and the thread running it)

    As a last resort to deal with potential hanging in the DB (Sybase), I'd like to
    find a way to stop the processing. I'm willing to violate some rule, such as calling
    Thread.stop. But that doesn't seem to drop the connection. Any suggestion how
    I can drop that connection? Thanks. /Bill

    Joe, as you know I also posted at Sybase/jdbc. I'm reposting the last post here
    for the benefits of anyone else might be interested in the thread.
    I tried out cancel and it essentially did the same thing as set timeout, except
    the time is more precise since the application controls it. Set timeout is more
    economical to operate though. I'll probably take one of these, which do solve
    half of the problem, for the time being until something better comes along. Unfortunately,
    though, the other half causes more problems because when that happens, other executions
    will pile on and get blocked as well.
    Joseph Weinstein <[email protected]> wrote:
    >
    >
    Bill wrote:
    As a last resort to deal with potential hanging in the DB (Sybase),I'd like to
    find a way to stop the processing. I'm willing to violate some rule,such as calling
    Thread.stop. But that doesn't seem to drop the connection. Any suggestionhow
    I can drop that connection? Thanks. /BillKilling the thread is bad for the server, because it only creates a fixed
    number of
    execute-threads to do user work... The things you should try are:
    1 - Call cancel() on the jdbc statement that is hanging. Call connection.close()
    on the connection. This requires having access to those objects from
    another
    thread.
    2 - Find out the spid of the hung DBMS session (either record it ahead
    of time or
    query the DBMS with another connection) and use T-SQL to kill that DBMS
    session.
    3 - Try resetting the pool.
    Joe

  • How do I add a printer connected to another iMac on the network to my printer list?

    How do I add an Epson printer connected to an iMac on the network to the printer list on my MacBook Pro? I cannot get it to show up in the list for printers to add.

    That only works if the printer is itself a network printer. You can't do it if it is directly connected to another computer on the network unless it is configured to be a Shared Printer on the other computer.

  • PC died and in turn my main iTunes library. iPhone was synced to it. Now when I try to connect to another library it tells me the phone must be wiped clean before I can manage music with new library. Any way around that? Don't want to lose music.

    My PC died and in turn so did my main iTunes library.  My iPhone was synced to the library that is gone.  Now when I try to connect to another library, it tells me the phone must be wiped clean before I can manage music with new library.  Any way around that?  I don't want to lose the music that is on my phone.  I am looking for a way to tell the phone to "forget" the old library and let me start working with a new library. 

    It has always been very basic to always maintain a backup copy of your computer for just such an occasion.
    Use your backup copy of your computer to put everything on the new one.
    It sounds like you have failed to do this, which is not good at all.
    You will have to transfer your itunes purchases from your iphone.  Authorize your computer for your itunes account 
    About iTunes Store authorization and deauthorization
    Open itunes, plug in iphone, do NOT sync, click File>Transfer Purchases
    When you do sync you will lose your pics ( photo library - synced from your old computer), your itunes content ( music, apps, videos,etc) , your contacts and your calendars.  So do NOT sync yet.  This is why a backup copy is so important.
    Enter one unique contact and calendar entry on your computer.
    When you first sync, you should get the option to merger the data.  Choose it.
    If you want your pics, then you will need to e-mail them to yourself before you sync.  They will not be of the original quality as they are reduced when synced to iphone.
    When all is as goos as it can be, then backup your computer, and always maintain the backup.

  • I have Words with Friends app on iphone and game on computer.  When I try to play with Facebook friends message says" Account Already Connected.  This Facebook account has been connected to another user."  How can I play game on iphone or my pc?

    I have Words with Friends app on my iphone4S and the same game on computer.  When I try to play Words with Friends with Facebook on the iphone the  message says" Account Already Connected.  This Facebook account has been connected to another user."  It is connected to my computer. How can I play game on iphone?

    Hi Grandmaz5,
    If you are having issues connecting to Facebook on your iPad, and you have already troubleshot the Facebook app itself, you may want to check the built-in iOS settings for Facebook; you may find the following article helpful:
    iOS: Using Facebook, Twitter, and other social network accounts
    http://support.apple.com/kb/HT5500
    Regards,
    - Brenden

  • The circuit of my macbook is dead yet the hard drive is fine.  I need to access a file from the hard drive, how can i do this? is there a cable i can connect to another mac that will let me transfer the file?

    The circuit of my macbook is dead yet the hard drive is fine.  I need to access a file from the hard drive, how can i do this? The mac turns on the screen freezes as bright blue.  Is there a cable i can connect to another mac that will let me transfer the file?

    There is another option if the Macbook will start up in Target Disk Mode.
    Restart the computer while holding down the T key. If you see the firewire symbol moving around on the screen you can connect this one to another one in TDM. You will need a suitable cable to connect the two Macs.
    http://support.apple.com/kb/ht1661
    Firewire symbol:

Maybe you are looking for