Starting threads

Hello all.
I'd like to ask a simple question regarding new threads creation.
I need to create a service that opens a new ServerSocket and keeps listening to it. When a new connection arrives, it should use a separated thread to handle the incoming connection. Quite like a HTTP Server.
I've read that you can't start new threads in the EJB container; so I got confused: where can I start threads? Or how? Can you please explain? Please, I need help with this and can use any pointer of where to look for an answer.
Thanks a lot.
Leo.

I believe you can set an option for oc4j to enable threads I think the option is -useThreads. You can then launch your socketserver from a servlet if you want.
Not sure if this is good practice or not, but I have heard of people doing it.

Similar Messages

  • Start Thread method behaviour

    I'm using Oracle 10
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining optionsI created two Java classes and a wrapper procedure.
    1. The first class timeOutSAPEntry has a delay caused by sleep method of 10 sec. then updates a row in table sap_entry.
    2. The second class createMonitorSAPEntry creates an instance of timeOutSAPEntry, call start() method and ends.
    3. And the wrapper procedure just calls createMonitorSAPEntry.
    My problem: when I call the wrapper procedure, it hangs for 10 sec (consequence of sleep method). But, I expected that the thread could be created, started and then the control returns to procedure and finishes immediatelly. You can see in the execution below the sysdate before and after the procedure call.
    Is there any solution? I would like the same behaviour of others JVM, where the main thread continues the execution and not hangs out waiting for the started thread.
    create or replace
           and compile java source named "timeOutSAPEntry"
    as
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    public class timeOutSAPEntry
        extends Thread{
        public void run(){
            try{
                 this.sleep(10000);
                 Connection conn =
                        DriverManager.getConnection("jdbc:default:connection:");
                 PreparedStatement  st = conn.prepareStatement("update cmforna.sap_entry set status = 'Failed' where Status = 'Sent'");
                 st.executeUpdate();
                 st.close();
                 conn.commit();
                 conn.close();      
            }catch(Exception e){
                e.printStackTrace();
    create or replace
           and compile java source named "createMonitorSAPEntry"
    as
    public class createMonitorSAPEntry{
       public static void create(){
            timeOutSAPEntry to = new timeOutSAPEntry();
            to.start();
    create or replace procedure create_monitor_post
    as
    language java name 'createMonitorSAPEntry.create()';
    SQL> insert into sap_entry
      2  (id, posted_on, status)
      3  values
      4  (6, sysdate, 'Sent');
    1 row created.
    SQL>
    SQL> commit;
    Commit complete.
    SQL>
    SQL> select to_char(sysdate, 'hh24:mi:ss') Before_Time from dual;
    BEFORE_T
    16:27:04
    SQL>
    SQL> exec create_monitor_post;
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select to_char(sysdate, 'hh24:mi:ss') After_Time from dual;
    AFTER_TI
    16:27:14
    SQL> Many tks,
    Miguel

    Add a KeyAdapter like this:
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent ke) {
        int key = ke.getKeyCode();
        if (key == KeyEvent.VK_LEFT) x1--;
        if (key == KeyEvent.VK_RIGHT) x1++;
    });*Note that I added this just after the bouncing = true; ... which is on about line 33.
    **Note that you will need to click in the Applet before the keys will function.
    ***Note that you will also likely want to slow down the balls.
    ~Bill

  • Error starting thread: Not enough storage is available to process...

    Hi all,
    We are seeing server going down frequently with below exception:
    [ERROR][thread ] Failed to start new thread
    [2010-04-08 14:36:54,046][ERROR][com.astrazeneca.portal.rss.ContentTransformer] - Error processing item:null
    ; SystemID: http://beaa.astrazeneca.net:10002/NewsBroker/resources/newsToRss.xsl; Line#: 21; Column#: 128
    javax.xml.transform.TransformerException: java.lang.Error: Error starting thread: Not enough storage is available to process this command.
         at org.apache.xalan.extensions.ExtensionHandlerJavaPackage.callFunction(ExtensionHandlerJavaPackage.java:403)
         at org.apache.xalan.extensions.ExtensionHandlerJavaPackage.callFunction(ExtensionHandlerJavaPackage.java:426)
         at org.apache.xalan.extensions.ExtensionsTable.extFunction(ExtensionsTable.java:220)
         at org.apache.xalan.transformer.TransformerImpl.extFunction(TransformerImpl.java:437)
         at org.apache.xpath.functions.FuncExtFunction.execute(FuncExtFunction.java:199)
         at org.apache.xpath.XPath.execute(XPath.java:268)
         at org.apache.xalan.templates.ElemVariable.getValue(ElemVariable.java:279)
         at org.apache.xalan.templates.ElemVariable.execute(ElemVariable.java:247)
    I have a weblogic support SR open and they suggested to add -XXtlaSize and -XXlargeObjectLimit to our JVM parameter. With these parameters, we are getting below error in Windows frequently:
    Reporting queued error: faulting application java.exe, version 1.5.0.11, faulting module jvm.dll, version 27.3.1.1, fault address 0x0014b442.
    I have seen few threads on Sun forum, but answer was not posted there. Details of our environment are as below:-
    JVM : JROCKIT 1.5.0.11
    OS : Windows 2003
    Application Server : Weblogic 10
    Any inputs or pointers will be highly appreciated as this is a bit urgent for me...
    Thanks & Regards,
    Sanjeev

    Hi Henrik,
    I am running Weblogic with below parameters now:
    -Xnohup -Xms:1536m -Xmx:1536m -XXtlaSize:min=32k,preferred=768k -XXlargeObjectLimit:32K
    Weblogic crashed again with below dump:
    ===== BEGIN DUMP =============================================================
    JRockit dump produced after 0 days, 07:17:18 on Fri May 07 15:26:16 2010
    Additional information is available in:
    E:\PortalLIVDomaina\jrockit.5772.dump
    E:\PortalLIVDomaina\jrockit.5772.mdmp
    If you see this dump, please open a support case with BEA and
    supply as much information as you can on your system setup and
    the program you were running. You can also search for solutions
    to your problem at http://forums.bea.com in
    the forum jrockit.developer.interest.general.
    Error Message: Illegal memory access. [54]
    Exception Rec: EXCEPTION_ACCESS_VIOLATION (c0000005) at 0x005148AF - memory at 0x00000000 could not be written.
    Minidump : Wrote mdmp. Size is 1406MB
    SafeDllMode : -1
    Version : BEA JRockit(R) R27.3.1-1_CR344434-89345-1.5.0_11-20070925-1628-windows-ia32
    GC Strategy : Mode: throughput. Currently using strategy: genparpar
    GC Status : OC currently running, in phase: sweeping. This is OC#3000.
    : YC is not running. Last finished YC was YC#9937.
    OC History : Strategy genparpar was used for OC#1.
    : Strategy singleparpar was used for OC#2.
    : Strategy genparpar was used for OC#3 to OC#3000.
    YC History : Ran 11 YCs before OC#2996.
    : Ran 18 YCs before OC#2997.
    : Ran 11 YCs before OC#2998.
    : Ran 8 YCs before OC#2999.
    : Ran 1 YCs before OC#3000.
    Heap : 0x00900000 - 0x60900000
    Compaction : 0x06900000 - 0x0C900000
    Could you please provide some input on this?
    Thanks,
    Sanjeev

  • HOW DO I START THREADS ALL AT ONCE? please help!

    HI! I was just wondering if anybody knew how to start threads all at once. There is the treadgroup stuff but the only method I see there is threadgroup.resume I would like something analogous to threadgroup.start
    any ideas?
    thanks,
    - cunduro

    I don't think you can start all threads at the same time. If what you need is to have all threads ready before they begin doing their job, in the run method you can call a method that waits on some object and when all threads are created (and running and waiting on the object) do a notifyAll(). In that moment all threads will resume working.

  • Starting threads in constructors

    Hi,
    This is kind of a general question. I have a class which initializes a thread within a constructor. e.g.,
    Class A {
             //Initialize thread prerequisites
            String name;
             Thread th;
           classConstructor(String threadName){
                    name = threadName;
                    th = new Thread(this, name);
                    System.out.println( "New Thread: " +th);          
                    th.start() ;
    }Is this the right way of using threads? Or should threads be started from the main method? What are the merits/demerits in these two approaches?
    Thanks!

    You can start threads from anywhere. After all, you're just creating another Java object and calling the start method on it.
    However, there are places where you shouldn't start threads. Unfortunately, in constructors of non-final classes is one of those places. And here's why...
    If you subclass your class, the subclass constructor will begin by calling one of the constructors in your class (either implicitly or explicitly). In this case, your constructor will create and begin a thread. That thread could potentially call methods on this new object instance (especially as in your case you have passed this to the thread, so it looks likely that it will). The problem is, because we're talking about threads, the thread might call the methods on your class before your constructor or the subclass constructor has completed, and you would therefore be calling methods on an incomplete object which might cause issues.
    For example:
    public abstract class A {
      public A() {
        // create and start thread here
      public abstract int getSomething();
    public class B extends A {
      private static int something;
      public B() {
        // implicitly calls A()
        something = 1;
      public int getSomething() {
        return something;
    }Now, if the thread you started calls getSomething(), the return value might be 0, or it might be 1, depending on how the thread executes in relation to the original thread which is executing the constructors.

  • Joining a Timer started thread

    Given a piece of code that uses a Timer to start a TimerTask, can the main thread get at the timer-started Thread so it can join() on it?

    thrice wrote:
    kajbj wrote:
    @Op.
    Why did you create a new Thread? Um, I'm not sure if you mean "thread" as in a new thread of Java code, or "thread" as in new topic on this forum!I meant thread as in topic.
    >
    I created new threads in my Java code because I need to get about 50 separate pieces of work done as concurrently as the hardware will allow, while still letting the main thread get work done.
    I created a separate topic in this forum because this is a specific question to which I'd like a specific answer!
    @All others. Please continue the discussion in the new thread [http://forums.sun.com/thread.jspa?threadID=5344116]
    Um, no, please answer this simple question in this thread! I don't know if join()ing to a Timer-started Thread object is the way to solve my overall problem. I suspect it isn't, and your suggestion to use a CountDownLatch reinforces that suspicion.A Timer is single threaded. It will not start 50 threads even if you have 50 timer tasks.
    >
    For my Java education, I'd like to know if I can join() to a Timer-started thread, and if so, how do I do it?See above.

  • MaterialMaster_CreateIDOC Cannot start thread

    I am using the Material_Master AOI template with data services I wanted to loop through the IDOC for each plant starting with our main plant then as we loop material would be pushed (extended) to the other plants. When I looped the second time I go the error below. It appears because the connection is already opened for the IDOC another cannot thread be created. Can I close the connection when each plant is pushed and then re-open for the next plant?
    7036       7160       SYS-050703         9/20/2011 2:47:24 PM    |Session Job_P2CMM01_Res_Material_Master|Work flow WF_P2CMM01_Res_MaterialMaster_GenerateIDOC|Data flow DF_P2CMM01_Res_MaterialMaster_CreateIDOC
    7036       7160       SYS-050703         9/20/2011 2:47:24 PM    Cannot start thread.

    Tasks are meant to be run in the context of a JavaFX application, like in the example below:
    import javafx.application.Application;
    import javafx.concurrent.Task;
    import javafx.scene.Scene;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import java.io.IOException;
    public class TaskApp extends Application {
      public static void main(String[] args) { launch(args); }
      @Override public void start(final Stage stage) throws IOException {
        //create task object
        Task<Integer> task = new Task<Integer>(){
          @Override
          protected Integer call() throws Exception{
            System.out.println("Background task started...");
            int iterations;
            for(iterations = 0; iterations < 10000; iterations++){
              if(isCancelled()){
                break;
              System.out.println("Iteration " + iterations);
              Thread.sleep(3000);
            return iterations;
        //start the background task
        Thread th = new Thread(task);
        th.setDaemon(true);
        System.out.println("Starting background task...");
        th.start();
        stage.setScene(new Scene(new StackPane(), 200, 100, Color.BLANCHEDALMOND));
        stage.show();
    }Also your code was setting the task thread as a daemon thread. The Java Virtual Machine exits when the only threads running are all daemon threads. So once your main routine finished (which would be really quickly), the program would just exit without doing anything much. Note that, in your example, even if you made the Task thread a non-daemon thread, it still doesn't work (likely because the Task class has some reliance on the JavaFX system being initialized). For your simple background process you could skip Task and just use a Runnable or a Callable (which doesn't require JavaFX and hence would work in a non-daemon thread invoked from main), but I guess it's just an experiment.

  • Starting Thread within its own constructor...

    this is maybe not critical, but is there a reason not to start a Thread
    like this. it is non-standard way:
    public class MyClass implements Runnable {
      public MyClass() {
        (new Thread((Runnable) this)).start();
    }that is an easy way to start a Thread with one line of code.
    does that violate any rules of self-reference in a Thread constructor?
    i am new to Threads thanks.

    I am no expert on this, so this is only opinion, but I'd be reluctant to do this as you will lose some flexibility here. If a class holds a variable of this type, it cannot instantiate the class at one location and start the thread at another. It also goes against the rule of expected behavior.
    Again, this my opinion only. I am very open to others' thoughts and corrections.

  • Wish to prevent application starting threads

    Hi,
    I wish to prevent my standalone java application from executing threads.
    I ensure the permission,      java.lang.RuntimePermission "modifyThreadGroup" is not in the policy file.
    According to http://java.sun.com/j2se/1.4.2/docs/guide/security/permissions.html, I believe the application should not be able to instantiate new thread objects.
    To test it, I run the code:
              Runnable tonyRunnable = new Runnable() {
                   public void run() {
                        System.out.println("tony says it's cool!");
              Thread t = new Thread(tonyRunnable);
              t.start();
              t.join();And it runs. I expect a security exception but don't get it. I am 100% confident my application has a security manager and policy file.
    Any ideas?
    Thanks.

    You're not doing anything with ThreadGroups in the code above. The modifyThreadGroup target of RuntimePermission is for allowing:
    "modification of thread groups, e.g., via calls to ThreadGroup destroy, getParent, resume, setDaemon, setMaxPriority, stop, and suspend methods"
    There is no way to prevent an application from creating and starting its own threads.

  • Starting thread numerous times

    hi, i got the following code:
    public class TestRunnerThread
      extends Thread
      private ThreadCheck test = null;
      public TestRunnerThread()
        test = new ThreadCheck();  // doesn't work - see run method.
      public static void main(
          String[] args_)
        TestRunnerThread runner = new TestRunnerThread();
        runner.start();
      public void run()
        while (true)
          try
            // ::NOTE:: thread only works with new instance - starting old thread
            // doesn't work anymore as soon as the thread leaves it's run method.
            // test = new ThreadCheck();  // this works
            test.start();
            System.out.println("waiting till join...alive:" + test.isAlive());
            test.join();
            System.out.println("sleep...");
            Thread.sleep(3000);
          catch (InterruptedException e)
            e.printStackTrace();
    public class ThreadCheck
      extends Thread
      boolean tester = false;
      public ThreadCheck()
        tester = true;
      public void run()
        System.out.println("#test:" + tester);
        System.out.println("#..............");
    }the ThreadChecker runs only if more than once if i create a new ThreadChecker object for every loop in the TestRunnerThread run method. although test.isAlive()) returns true even if i initialize the ThreadChecker only once in the TestRunnerThread run method which confuses me. isn't it possible to start the thread again as soon as it left the run method? and if so, why does it still say true for isAlive?
    cheers,
    mischka

    Hi,
    A thread that has terminated can't be re-started.
    /Kaj

  • Can't start Thread from modal JDialog.

    Hi,
    this is a part of my code. I can't start the scanThread from the object WaitingDl. But if i close the modal JDialog (WaitingDl) the scanThread starts, please help:
    Thread scanThread = new Thread() {
    public void run() {                       
    // do something ....
    WaitingDl waitFrame = new WaitingDl("Waiting process", parent, scanThread, "Please wait ...");
    class WaitingDl extends JDialog {
    public WaitingDl(String title, JFrame parent, Thread thread, String waitingText) {  
    // a modal Dialog
    super(parent,true);
    // This command doesn't work!
    scanThread.start();
    Thanks!

    Hi,
    As suggestion :
    I think your JDialog is modal and visible by default, so
    when you invoke the contructor :
    WaitingDL d=new ......
    you enter to "modal state" so the Event thread is blocked and this append when you invoke super at
    contructor level.
    If you set your dialog not visible you can do :
    WaitingDL d=new .........
    // at this moment the contructor is invoked but the event thread is not blocked so your thread is started
    d.setVisible(true);
    // at this point the dialog is visible you enter at a modal state but your thread is running
    Hope this help
    Bye

  • Re-starting Threads

    I am trying to reuse a pool of threads..
    Sometimes the threads report an IllegalThreadState exception when I try to (re) start a thread.
    The threads have finite loops and I know that they are done..But why do I keep getting these exceptions ?
    Thanks for any inputs..
    S
    Here's my worker thread code:
    <pre>
    class WorkerThread extends Thread
    boolean bIdle = true;
    private Object theJob = null;
    private ThreadPool threadPool;
    public WorkerThread( String strName, ThreadPool threadPool )
    setName( strName );
    this.threadPool = threadPool;
    public void run()
    for( int i = 0; i < 10; i++ )
    System.out.println( getName() + " VAL : " + i );
    try{
    sleep( 5 * 1000 );
    catch( InterruptedException ie ){
    System.out.println( "Someone kicked us out of here.." );
    ie.printStackTrace();
    System.out.println( "Done.." + getName() );
    bIdle = true;
    threadPool.returnWorker( this );
    return;
    public synchronized void setIdle( boolean bIdle )
    this.bIdle = bIdle;
    public synchronized boolean getIdle()
    return bIdle;
    public synchronized void setJob( Object aJob )
    theJob = aJob;
    public synchronized Object getJob()
    return theJob;
    </pre>

    Are you aware that the usual way of re-using threads is to not let them die? You usually have them wait untill there is another job ready.
    Here is an example thread pool, it's a server. The number of threads grows on demand.
    *: net/turingcomplete/phosphor/shared/josh_empty_class.java
    * Version 1.0
    * April 26, 2001
    * Copyright � 2001 turingcomplete.net. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * 1. Redistributions of source code must retain the above copyright
    * notice, this list of conditions and the following disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in
    * the documentation and/or other materials provided with the
    * distribution.
    * 3. The end-user documentation included with the redistribution,
    * if any, must include the following acknowledgment:
    * "This product includes software developed by
    * turingcomplete.net (http://turingcomplete.net/)."
    * Alternately, this acknowledgment may appear in the software itself,
    * if and wherever such third-party acknowledgments normally appear.
    * 4. The names "Phosphor" and "turingcomplete.net" must
    * not be used to endorse or promote products derived from this
    * software without prior written permission. For written
    * permission, please contact [email protected].
    * 5. Products derived from this software may not be called "Phosphor",
    * nor may "Phosphor" appear in their name, without prior written
    * permission of turingcomplete.net.
    * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
    * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
    * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
    * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    * SUCH DAMAGE.
    * ====================================================================
    package net.turingcomplete.phosphor.shared;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    * Abstracts an generic server that uses a growable thread pool. The XML protocol makes
    * adding state to the protocol difficult. The protocol tries to be stateless as much
    * as possible, and it works quite well.
    * <p>
    * REVISION HISTORY:
    * <p>
    * @version 1.0, April 26, 2001
    * @see ####
    * @since 1.0
    abstract public class ThreadPool extends Thread {
         /** returns a thread that is able to serve connections */
         abstract protected ConnectionHandler createNewThread();
         /** returns whether a connection to this ip is okay, or it is banned, should be
         * overrided in subclasses
         protected boolean isConnectionAcceptable(InetAddress inet) {
              return true;
         private List myPool = new ArrayList();
    private List myWaitingThreads = new Vector();
    private List myBusyThreads = new Vector();
    private List myAllThreads = new Vector();
    protected int myMaxConnections, myPort, myQueueLength;
    protected volatile boolean myKeepRunning = true;
         private ServerSocket myClientConnections = null;
    public ThreadPool(int port, int queueLength, int maxConnections, ThreadGroup threadGroup) {
              super(threadGroup, "ThreadPool");
    myMaxConnections = maxConnections;
              myPort = port;
    myQueueLength = queueLength;
         public ThreadPool(int port, int queueLength, int maxConnections) {
    this(port, queueLength, maxConnections, Thread.currentThread().getThreadGroup());
    final public void run() {
    Trace.thread(this);
    try {
    ServerSocket myClientConnections = new ServerSocket(myPort, myQueueLength);
    myClientConnections.setSoTimeout(Integer.MAX_VALUE); // so we can interrupt
    Trace.display("Accepting connections on port " + myClientConnections.getLocalPort() +
                                       "\tHost "+myClientConnections.getInetAddress());
    while(myKeepRunning) {
    try {
    Trace.debug("Waiting threads " + myWaitingThreads.size() + "\tnon-waiting threads: "
    + myBusyThreads.size());
    Socket connection = myClientConnections.accept();
    if(myWaitingThreads.isEmpty() && myBusyThreads.size() >= myMaxConnections) {
                                  Trace.display("Max connections reached, refusing connection");
                                  refuseConnection(connection);
                             } else if (!isConnectionAcceptable(connection.getInetAddress())) {
                                  connectionBanned(connection);
                             } else {
    if(myWaitingThreads.isEmpty()) {
    ConnectionHandler handler = createNewThread();
    handler.start();
    myAllThreads.add(handler);
    myBusyThreads.add(handler);
                                  try {
                                       connection.setKeepAlive(true); // // so we will recognize server crashes
                                  } catch (SocketException e) {
                                       Trace.display(e, "Cannot set SO_KEEPALIVE");
    synchronized(myPool) {
    myPool.add(connection);
    myPool.notifyAll();
    } catch (InterruptedIOException e) {
    Trace.display(e, "harmless, interupted ServerSocket.accept");
    } catch (IOException e) {
    Trace.display(e, "Could not start server. Port occupied.");
    } finally {
    synchronized(myAllThreads) {
    Iterator i = myAllThreads.iterator();
    while(i.hasNext()) {
    ConnectionHandler thread = (ConnectionHandler)i.next();
    thread.stopRunning();
    Trace.threadEnd(this);
         protected void refuseConnection(Socket s) {
              try {
                   Trace.display("Connection refused to "+s.getInetAddress()+" " + s.getPort() +
                        ", max connections: " + myMaxConnections+ " reached.");
                   Writer out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8"));
                   out.write(ProtocolDetails.XMLDeclaration("UTF-8"));
                   out.write(ProtocolDetails.beginStream(ProtocolDetails.LOADSERVER_NAME));
                   out.write(XMLString.tag("connectionRefused", XMLString.attr("type", "503") +
                                       XMLString.attr("description", "Server is full") +
                                       XMLString.attr("maxUsers", String.valueOf(myMaxConnections))));
                   out.write(XMLString.endTag("stream"));
                   out.flush();
                   s.close();
              } catch (IOException e){
                   Trace.display(e, "Cannot send connection refused message.");
         protected void connectionBanned(Socket s) {
              try {
                   Trace.display("Connection refused to "+s.getInetAddress()+" " + s.getPort() +
                        ", IP banned.");
                   Writer out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8"));
                   out.write(ProtocolDetails.XMLDeclaration("UTF-8"));
                   out.write(ProtocolDetails.beginStream(ProtocolDetails.LOADSERVER_NAME));
                   out.write(XMLString.tag("connectionRefused", XMLString.attr("type", "504") +
                                       XMLString.attr("description", "You are banned from this server")));
                   out.write(XMLString.endTag("stream"));
                   out.flush();
                   s.close();
              } catch (IOException e){
                   Trace.display(e, "Cannot send connection refused message.");
    protected void stopRunning() {
    myKeepRunning = false;
              interrupt();
              if(myClientConnections != null)
                   try {
                        myClientConnections.close();
                   } catch (IOException e) {
                        Trace.display(e, "harmless, can't close");
         // returns the list of active connections -- XXX will cause problems if
         // caller adds or removes elements
         public List getConnections() {
              return myBusyThreads;
         // returns the snapshot of current active connections
         public List getCurrentConnections() {
              return new ArrayList(myBusyThreads);
    abstract protected class ConnectionHandler extends Thread {
              /** if any initialization needs to be done while still synchronized with other threads */
    abstract protected void receivedConnection();
              /** do any handshaking that must be done before regular (stateless) output is sent */
              abstract protected void initProtocol(Writer out) throws IOException;
              /** serve the connection */
    abstract protected void serve(InputStream in) throws IOException;
              /** returns whether there was any activitity since last timeout. Should be overriden
              * by subclasses that have other activity other then read & write to the socket like so:
              * return myIsActivity || super.wasActivity();
              protected boolean wasActivity() {
                   return myWasActivity.get();
              /** the socket connection */
    protected Socket myConnection = null;
              /** myOut should be accessed through send(), and should be synchronized while calling sendNoFlush, as to keep tags from
                   getting messed up */
              protected Writer myOut = null;
              private List mySendBuffer = new Vector();
    private volatile boolean myKeepRunning = true;
              private boolean myIsStreamClosed; // to make sure we only send </stream> once
              private Timer myActivityTimeoutTimer = new Timer(true);
              private MutableBoolean myWasActivity = new MutableBoolean(false);
              int myIdleTimeout;
              private String myEncoding;
              public ConnectionHandler(int idleTimeout, String encoding) {
                   myIdleTimeout = idleTimeout;
                   myEncoding = encoding;
                   if (myIdleTimeout > 0)
                        myActivityTimeoutTimer.schedule(new NoActivityTimeout(), myIdleTimeout, myIdleTimeout);
    final public void run() {
    Trace.thread(this);
    stopRunning:
    while(myKeepRunning) {
    myConnection = null;
    synchronized(myPool) {
    while(myPool.isEmpty()) {
    if(!myKeepRunning)
    break stopRunning;
    myWaitingThreads.add(this);
    myBusyThreads.remove(this);
    try {
    myPool.wait();
    } catch (InterruptedException e) {
    Trace.display(e, "Harmless, interrupted myPool.wait()");
    myBusyThreads.add(this);
    myWaitingThreads.remove(this);
    myConnection = (Socket)myPool.remove(myPool.size() - 1);
                             myWasActivity.set(true);
                             myIsStreamClosed = false;
    receivedConnection();
    try {
                             Writer out = new BufferedWriter(new OutputStreamWriter(myConnection.getOutputStream(), myEncoding));
                             out.write(ProtocolDetails.XMLDeclaration(myEncoding));
                             initProtocol(out);
                             out.flush();
                             myOut = out;
                             flushSendBuffer();
    serve(new NotifyActivityInputStream(myConnection.getInputStream()));
    } catch (IOException e) {
    Trace.display(e, "Closing connection to "+myConnection.getInetAddress());
                        } finally {
                             closeStream();
                             myActivityTimeoutTimer.cancel();
                   myBusyThreads.remove(this);
    myWaitingThreads.remove(this);
                   Trace.threadEnd(this);
              // will stop running and close connection
    public void stopRunning() {
    myKeepRunning = false;
    interrupt();
                   closeStream();
              public void stopRunningAfterConnection() {
    myKeepRunning = false;
    interrupt();
              synchronized protected void send(String s) throws IOException {
                   myWasActivity.set(true);
                   if(myOut != null) {
                        myOut.write(s);
                        myOut.flush();
                   } else
                        mySendBuffer.add(s);
              /** if calling sendNoFlush, myOut should be synchronized till you are ready to flush the stream,
              * the output may not be sent in the proper order
              synchronized protected void sendNoFlush(String s) throws IOException {
                   if(myOut != null) {
                        myOut.write(s);
                   } else {
                        mySendBuffer.add(s);
              /** so other threads can call send before myOut has been intialized, should
              * be called in serve() after any handshaking is done*/
              synchronized private void flushSendBuffer() throws IOException {
                   Assert.that(myOut != null);
                   Iterator i = mySendBuffer.iterator();
                   while (i.hasNext()) {
                        sendNoFlush((String)i.next());
                   mySendBuffer.clear();
                   myOut.flush();
              synchronized protected void closeStream() {
                   if (!myIsStreamClosed) {
                        try {
                             send(XMLString.endTag("stream"));
                             myIsStreamClosed = true;
                        } catch (IOException e) {
                             Trace.display(e);
                   if (myConnection != null)
                        try {
                             myConnection.close();
                        } catch (IOException e) {
                             Trace.display(e, "harmless, can't close connection to "+myConnection.getInetAddress());
              /** used to notify ConnectionTo that there was read activity on the stream */
              protected class NotifyActivityInputStream extends FilterInputStream {
                   NotifyActivityInputStream(InputStream in) {
                        super(in);
                   public int read(byte[] b) throws IOException {
                        int numRead = in.read(b);
                        myWasActivity.set(true); // set after the read, as read() may block forever
                        Trace.read(b, 0, numRead);
                        return numRead;
                   public int read(byte[] b, int off, int len) throws IOException {
                        int numRead = in.read(b, off, len);
                        myWasActivity.set(true);
                        Trace.read(b, off, numRead);
                        return numRead;
                   public int read() throws IOException {
                        int c = in.read();
                        myWasActivity.set(true);
                        return c;
              }///:>
              /** will close the stream if no activity occured within myIdleTimeout ms */
              public class NoActivityTimeout extends TimerTask {
                   public void run() {
                        if(!wasActivity()) {
                             Trace.display("Closing clientTo connection because of inactivity.");
                             try {
                                  send(XMLString.tag("disconnect", XMLString.attr("type", "420") +
                                                                     XMLString.attr("description", "Idle timout of "+myIdleTimeout+" ms reached.")));
                             } catch (IOException e) {
                                  Trace.display(e, "Can't send disconnect message");
                             closeStream();
                        myWasActivity.set(false);
              }///:>
    }///:>
    }///:~

  • Starting threads in background?

    I am trying to address the issue where I have a somewhat
              time-consuming server-side operation, and I don't want the
              browser to time out, etc. So, I want to use a the html
              meta-refresh capability to keep the browser happy,
              and possibly send it some percent completed status info, etc.
              But to do this, it seems like I need to be able to start another
              thread on the server which will do the work, which the
              session thread can monitor, etc.
              Is there a certain way within weblogic that threads should be
              created etc., or is it allowed at all. I know that it is not
              allowed to start new threads within EJB code. What about
              within JSP's and JavaBeans?
              Thanks,
              Jason
              

    You can just redirect using the response object, however sometimes you may
              want to do some fancier stuff with JavaScript, that is all I meant.
              > I am not clear on how you are able to detect when "processing..."
              > is completed. Do you use a meta refresh to spin until the
              > processing is done on the server side, and then redirect?
              Basically, yes. There are really two things to do:
              1) Displaying status of processing (not started, in progress, done)
              2) Refreshing if not done
              For example, if you identify the task as 1752324, your URL might be:
              http://myco.com/myapp/showstatus-1752324.proc
              Or:
              http://myco.com/myapp/showstatus?id=1752324
              The point is that the same URL could show:
              "Has not started yet"
              Then:
              "Is in phase 1"
              Then:
              "Is in phase 2"
              Then:
              "Is finished"
              And if the user refreshes the page in the browser or saves off the URL and
              visits it later or whatever, the process itself will not be repeated, just
              the status will be displayed
              Cameron Purdy
              [email protected]
              http://www.tangosol.com
              WebLogic Consulting Available
              "Jason Rosenberg" <[email protected]> wrote in message
              news:[email protected]...
              > Cameron,
              >
              > It seems like your response below is something you like to cut and
              > paste and post repeatedly...But can you augment it a little to explain
              > the second part of step 3, the "uses javascript to redirect" part?
              >
              > I am not clear on how you are able to detect when "processing..."
              > is completed. Do you use a meta refresh to spin until the
              > processing is done on the server side, and then redirect?
              >
              > Or what?
              >
              > I am not that familiar yet with JavaScript, does it have built in
              > functionality to do this? I am guessing not, since it is entirely
              > client-side....
              >
              > Jason
              >
              >
              > "Cameron Purdy" <[email protected]> wrote in message
              > news:[email protected]...
              > > 1) The work to be done is assigned a uid or something similar to
              prevent
              > it
              > > from being done twice
              > > 2) The user presses the button which passes the uid in a hidden field
              > (for
              > > example)
              > > 3) The serlvet responds by kicking off the big process with jms and
              sends
              > > back a page that displays a "processing..." message and uses javascript
              to
              > > redirect (with a place to click just in case javascript is turned off)
              > > 4) The url redirected to includes the uid to identify the process for
              > which
              > > the result is desired
              > > 5) When the process is completed, the information is placed in some
              known
              > > location (e.g. HttpSession or database) and the pending request to find
              > the
              > > result can return the result
              > >
              > > --
              > >
              > > Cameron Purdy
              > > [email protected]
              > > http://www.tangosol.com
              > > WebLogic Consulting Available
              > >
              > >
              > > "Jason Rosenberg" <[email protected]> wrote in message
              > > news:[email protected]...
              > > > I am trying to address the issue where I have a somewhat
              > > > time-consuming server-side operation, and I don't want the
              > > > browser to time out, etc. So, I want to use a the html
              > > > meta-refresh capability to keep the browser happy,
              > > > and possibly send it some percent completed status info, etc.
              > > >
              > > > But to do this, it seems like I need to be able to start another
              > > > thread on the server which will do the work, which the
              > > > session thread can monitor, etc.
              > > >
              > > > Is there a certain way within weblogic that threads should be
              > > > created etc., or is it allowed at all. I know that it is not
              > > > allowed to start new threads within EJB code. What about
              > > > within JSP's and JavaBeans?
              > > >
              > > > Thanks,
              > > >
              > > > Jason
              > > >
              > > >
              > >
              > >
              >
              >
              

  • [solved]Yet Another "X won't start" thread

    I get the black screen when i try to startx. i followed the wiki entry to set up X, but it doesn't work. Now, what i want to know is, how do i go back on a fresh install to an older version of X, that *doesn't* use HAL?
    Last edited by GypsyJoker (2009-11-28 01:05:05)

    It happened to me too. I use LXDE and everything was fine until last X.org update (prior to today's) when the blank screen started happening after every restart. I discovered that if I edit /etc/xdg/lxsessions/LXDE/autostart file as root and close it, even without changing anything, not resaving the file, not doing anything to it, then I was able to enter to X with startx as always. Weird, isn't it?
    Afortunately, today I've updated my x.org server and seems everything is fine again.
    Last edited by david.ptm56 (2009-11-21 18:33:22)

  • Another SAP won't start thread.

    Hello All
    I've just created a new instance TST as copy of my production system using the SAVLIB / RSTLIB method. I followed very carefully Volker's document. However the new system will not start. We are 4.6C with 4.6D EBCDIC Ext kernel on V5R3.
    Help!
    Here is my sapstart log
    ***********Beginning of data*************                                                                               
    SAP-R/3-Startup Program V1.7 (92/10/21)                                         
    Starting at 2006/07/11 16:07:12                                                 
    Startup Profile: "/usr/sap/TST/SYS/profile/START_DVEBMGS55_sapdevdb"                                                                               
    Execute Pre-Startup Commands                                                    
    (8207) Local: £(DIR_EXECUTABLE)/CLEANIPC 55 remove                              
    Exception SAP0451 in file /build/bas/46D/gen/opt/sapo4start.c line 1092         
    Could not resolve #(DIR_EXECUTABLE)/CLEANIPC                                    
    (8207) Local: CLRLIB LIB(R3WRK55)                                               
    (8207) Local: £(DIR_EXECUTABLE)/SAPMSCSA pf=£(DIR_PROFILE)/TST_DVEBMGS55_sapdevdb
    Exception SAP0451 in file /build/bas/46D/gen/opt/sapo4start.c line 1092         
    Could not resolve #(DIR_EXECUTABLE)/SAPMSCSA
    Starting Programs                                                                               
    memafn_group parm: 0                                                                               
    (8207) Starting remote Command:                                                                               
    Host:     sapdevdb                                                                               
    Username:                                                                               
    Password:                                                                               
    Command:  £(DIR_EXECUTABLE)/DLTOLDPKGS                                                                               
    TST                                                                               
    (8207) execute SBMJOB CMD(CALL PGM(£(DIR_EXECUTABLE)/DLTOLDPKGS) TST) JOB(JOBD) SYSLIBL(CURRENT) CURLIB(CURRENT) INLLIBL(CURRENT
    Exception CPF0006 in file /build/bas/46D/gen/opt/sapo4start.c line 1017                                                            
    Errors occurred in command.                                                                               
    (8207) Remote Command started.                                                                               
    (8207) Remote Command ended with exitcode (-1).                                                                               
    (8207) Starting local Command:                                                                               
    Command: £(_MS) pf=£(DIR_PROFILE)/TST_DVEBMGS55_sapdevdb                                                                          
    Job started:                                                                                Exception SAP0451 in file /build/bas/46D/gen/opt/sapo4start.c line 2080                                        
    Could not resolve #(_MS)                                                                               
    (8207) **** Failed to create new Child Process. Data was truncated on an input, output or update operation. ****
    (8207) Parent Shutdown at 2006/07/11 16:07:12                                                                               
    Execute Post-Shutdown Commands                                                                               
    (8207) Local: £(DIR_EXECUTABLE)/CLEANIPC 55 remove                                                             
    Exception SAP0451 in file /build/bas/46D/gen/opt/sapo4start.c line 1092                                        
    Could not resolve #(DIR_EXECUTABLE)/CLEANIPC                                                                   
    (8207) Local: CLRLIB LIB(R3WRK55)                                                                               
    (8207) Exiting with Return-Code -110. (Internal error)                                                         
    ***********End of Data*******************

    Hello Steve,
    you should check 2 things here.
    1. the job you used to view or edit IFS files. It needs to have CCSID(500). Check it with DSPJOB, option 2.
    2. check the IFS file you are working on. It also need to have a given codepage (500=EBCDIC, 819=ASCII or 1208=Unicode, depending on the kernel you are using).
    Best regards,
    René Lang
    SAP on IBM i5 Development

Maybe you are looking for

  • Can no longer sync my BB with my Outlook email..?

    I have already called my cell service provider which was of no help except to ask me to update my software (which I did), reboot (which I did), but still cannot syn the two together..This all since I had my power cut in my house about a week ago..Can

  • How can we handle the flatfile having the '~' as delimmiter in LSMW?

    Hi i have flat file which is having twenty fields which r seperated by '~' how we can handle it in LSMW thanks

  • Printing photos on HP8600 Pro

    It is easy to scan photos from the flatbed, but how to I get  the printer to increase the size of the oirginal photo to a desired level?

  • How to multiplex datafiles, controlfiles on different disks?

    Hi, Sir... I want my database to have two control files, data files on different disks.. In XE, after installation, data files, control files as follows (you know).. D:\Oracle\XE\oradata\XE\Control.DBF, SYSAUX.DBF, SYSTEM.DBF, TEMP.DBF, UNDO.DBF, USE

  • Printer won't print alignment page

    I have a new HP Officejet 4500g and am setting it up on a Windows Vista (32 bit) system.  The print is brand new and after I set it up and installed the ink cartridges it asked me to hit 'OK'  to print an alignment page.  It pulled in a piece of pape