MultiThread

Hi all,
Please let me know the details of the following.
1.What is Multi-Threading?
2. How it is useful to increase the Performance of a SQL query.( How it is useful
in Optimizing the query.
3. How we'll use MultiThread concept in Partitions and Using Processors.
Thanks in advance.

Your questions are off topic for this group and for OTN.
Further this group is not intended to substitute for not studying in class. I would not be surprised if you are sitting an exam and texting out hoping to get us to give you answers.
Next time do your homework.
If you are not a student ... become one.

Similar Messages

  • Video transmission with multithreading. I am having a problem?

    I am doing an application for sending video streams to multiple clients at the same time. So am using multithreading. I have the following codes to do the transmission. When I am using it with one thread only it is working fine. But when I use it with more threads for multiple transmissions I am have an error saying �Unable to realize com.sun.media.ProcessEngine�. Can anyone help me plz.
    import java.awt.*;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import java.io.*;
    import java.lang.Thread;
    public class VideoTransmitThread extends Thread{
    // Input MediaLocator
    // Can be a file or http or capture source
    private MediaLocator locator;
    private String ipAddress;
    private String port;
    private Processor processor = null;
    private DataSink rtptransmitter = null;
    private DataSource dataOutput = null;
    public VideoTransmitThread(MediaLocator locator,
                   String ipAddress,
                   String port) {
         this.locator = locator;
         this.ipAddress = ipAddress;
         this.port = port;
    * Starts the transmission. Returns null if transmission started ok.
    * Otherwise it returns a string with the reason why the setup failed.
    //run method for the thread
    public void run( ) {
         String result;
         // Create a processor for the specified media locator
         // and program it to output JPEG/RTP
         result =createProcessor();
         if (result != null)
         System.out.println("error: "+result);
         // Create an RTP session to transmit the output of the
         // processor to the specified IP address and port no.
         result =createTransmitter();
         if (result != null) {
         processor.close();
         processor = null;
         //return result;
         System.out.println("error: "+result);
         System.exit(0);
         try {
         Thread.sleep(1000); // 100 msec
         } catch (InterruptedException e) {
         return;
         // Start the transmission
         processor.start();
    * Stops the transmission if already started
    public void stop1() {
         synchronized (this) {
         if (processor != null) {
              processor.stop();
              processor.close();
              processor = null;
              rtptransmitter.close();
              rtptransmitter = null;
    private String createProcessor() {
         if (locator == null)
         return "Locator is null";
         DataSource ds;
         DataSource clone;
         try {
         ds = Manager.createDataSource(locator);
         } catch (Exception e) {
         return "Couldn't create DataSource";
         // Try to create a processor to handle the input media locator
         try {
         processor = Manager.createProcessor(ds);
         } catch (NoProcessorException npe) {
         return "Couldn't create processor";
         } catch (IOException ioe) {
         return "IOException creating processor";
         // Wait for it to configure
         boolean result = waitForState(processor, Processor.Configured);
         if (result == false)
         return "Couldn't configure processor";
         // Get the tracks from the processor
         TrackControl [] tracks = processor.getTrackControls();
         // Do we have atleast one track?
         if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";
         boolean programmed = false;
         // Search through the tracks for a video track
         for (int i = 0; i < tracks.length; i++) {
         Format format = tracks.getFormat();
         if ( tracks[i].isEnabled() &&
              format instanceof VideoFormat &&
              !programmed) {
              // Found a video track. Try to program it to output JPEG/RTP
              // Make sure the sizes are multiple of 8's.
              Dimension size = ((VideoFormat)format).getSize();
              float frameRate = ((VideoFormat)format).getFrameRate();
              int w = (size.width % 8 == 0 ? size.width :
                        (int)(size.width / 8) * 8);
              int h = (size.height % 8 == 0 ? size.height :
                        (int)(size.height / 8) * 8);
              VideoFormat jpegFormat = new VideoFormat(VideoFormat.JPEG_RTP,
                                       new Dimension(w, h),
                                       Format.NOT_SPECIFIED,
                                       Format.byteArray,
                                       frameRate);
              tracks[i].setFormat(jpegFormat);
              System.err.println("Video transmitted as:");
              System.err.println(" " + jpegFormat);
              // Assume succesful
              programmed = true;
         } else
              tracks[i].setEnabled(false);
         if (!programmed)
         return "Couldn't find video track";
         // Set the output content descriptor to RAW_RTP
         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
         processor.setContentDescriptor(cd);
         // Realize the processor. This will internally create a flow
         // graph and attempt to create an output datasource for JPEG/RTP
         // video frames.
         result = waitForState(processor, Controller.Realized);
         if (result == false)
         return "Couldn't realize processor";
         // Set the JPEG quality to .5.
         setJPEGQuality(processor, 0.5f);
         // Get the output data source of the processor
         dataOutput = processor.getDataOutput();
         return null;
    // Creates an RTP transmit data sink. This is the easiest way to create
    // an RTP transmitter. The other way is to use the RTPSessionManager API.
    // Using an RTP session manager gives you more control if you wish to
    // fine tune your transmission and set other parameters.
    private String createTransmitter() {
         // Create a media locator for the RTP data sink.
         // For example:
         // rtp://129.130.131.132:42050/video
         String rtpURL = "rtp://" + ipAddress + ":" + port + "/video";
         MediaLocator outputLocator = new MediaLocator(rtpURL);
         // Create a data sink, open it and start transmission. It will wait
         // for the processor to start sending data. So we need to start the
         // output data source of the processor. We also need to start the
         // processor itself, which is done after this method returns.
         try {
         rtptransmitter = Manager.createDataSink(dataOutput, outputLocator);
         rtptransmitter.open();
         rtptransmitter.start();
         dataOutput.start();
         } catch (MediaException me) {
         return "Couldn't create RTP data sink";
         } catch (IOException ioe) {
         return "Couldn't create RTP data sink";
         return null;
    * Setting the encoding quality to the specified value on the JPEG encoder.
    * 0.5 is a good default.
    void setJPEGQuality(Player p, float val) {
         Control cs[] = p.getControls();
         QualityControl qc = null;
         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
         // Loop through the controls to find the Quality control for
         // the JPEG encoder.
         for (int i = 0; i < cs.length; i++) {
         if (cs[i] instanceof QualityControl &&
              cs[i] instanceof Owned) {
              Object owner = ((Owned)cs[i]).getOwner();
              // Check to see if the owner is a Codec.
              // Then check for the output format.
              if (owner instanceof Codec) {
              Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
              for (int j = 0; j < fmts.length; j++) {
                   if (fmts[j].matches(jpegFmt)) {
                   qc = (QualityControl)cs[i];
                   qc.setQuality(val);
                   System.err.println("- Setting quality to " +
                             val + " on " + qc);
                   break;
              if (qc != null)
              break;
    * Convenience methods to handle processor's state changes.
    private Integer stateLock = new Integer(0);
    private boolean failed = false;
    Integer getStateLock() {
         return stateLock;
    void setFailed() {
         failed = true;
    private synchronized boolean waitForState(Processor p, int state) {
         p.addControllerListener(new StateListener());
         failed = false;
         // Call the required method on the processor
         if (state == Processor.Configured) {
         p.configure();
         } else if (state == Processor.Realized) {
         p.realize();
         // Wait until we get an event that confirms the
         // success of the method, or a failure event.
         // See StateListener inner class
         while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
              try {
              getStateLock().wait();
              } catch (InterruptedException ie) {
              return false;
         if (failed)
         return false;
         else
         return true;
    * Inner Classes
    class StateListener implements ControllerListener {
         public void controllerUpdate(ControllerEvent ce) {
         // If there was an error during configure or
         // realize, the processor will be closed
         if (ce instanceof ControllerClosedEvent)
              setFailed();
         // All controller events, send a notification
         // to the waiting thread in waitForState method.
         if (ce instanceof ControllerEvent) {
              synchronized (getStateLock()) {
              getStateLock().notifyAll();
    * Sample Usage for VideoTransmitNew class
    public static void main(String [] args) {
         // We need three parameters to do the transmission
         // For example,
         // java VideoTransmitNew file:/C:/media/test.mov 129.130.131.132 42050
         System.err.println("Start transmission");
         //Create a video transmit object with the specified params.
    MediaLocator URL=new MediaLocator("file:///C:/media/test.mpg");
    //Am using 3 different threads.
         new VideoTransmitThread(URL,"CSELAB12PC10","9876").start();
         new VideoTransmitThread(URL," CSELAB12PC11","9870").start();
         new VideoTransmitThread(URL," CSELAB12PC12","9690").start();
         //close all transmission before quiting.

    Hm, that was my silver bullet. Other than doing an uninsall and then installing Presenter again, you may need to reach out to Adobe and see if they can identify what could be causing this.

  • Pro*c multithreaded application has memory leak

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

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

  • How to configure ENV and DB for multithreaded application?

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

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

  • Multithreading - writing to file

    How can I get to write the Thread name, date and time to a file with the same thread name?
    What would I need to do to write the same information 1000 times to the file? Thank you.
    import java.lang.Thread;
    import java.lang.InterruptedException;
    public class RiveraThreadsMain {
        public static void main(String[] args) {
          System.out.println("Creating threads");
          Thread riverathread0 = new Thread (new RiveraThreads ("riverathread0"));
          Thread riverathread1 = new Thread (new RiveraThreads ("riverathread1"));
          Thread riverathread2 = new Thread (new RiveraThreads ("riverathread2"));
          System.out.println("Threads created, starting tasks.");
          riverathread0.start(); // invokes thread1's run method
          riverathread1.start(); // invokes thread2's run method
          riverathread2.start(); // invokes thread3's run method
          try
           Thread.currentThread() .sleep (10000);
          catch (InterruptedException e)
            e.getStackTrace();
             System.out.printf (
             "terminated prematurely due to interruption");
          System.out.println("Tasks started, main thread ends. \n");   
        } // end main
    import java.io.File;
    import java.io.IOException;
    import java.util.NoSuchElementException;
    import java.io.FileNotFoundException;
    import java.util.Formatter;
    import java.util.NoSuchElementException;
    import java.util.Calendar;
    import java.util.Scanner;
    public class RiveraThreads implements Runnable {
    Thread launcher;
    private String taskName;
    private Scanner input;
    private Formatter output;
    // empty constructor
    public RiveraThreads (){
      public RiveraThreads (String threadName)
        launcher = new Thread ( this, threadName );
        System.out.println ( launcher.getName());
        launcher.start();
       // taskName = name; // set task name
      public void run ()
        //System.out.println(Thread.currentThread().getName());
        try
          Calendar dateTime = Calendar.getInstance();
        //  output = new Formatter (new File (launcher.getName() ));
          input = new Scanner( new File( launcher.getName() ) ); 
          output = new Formatter (new File ( launcher.getName() ));
          System.out.printf( launcher.getName() + "%tc\n", dateTime );
        }// end try
        catch ( NoSuchElementException exception)
            exception.getStackTrace();
            System.out.printf ( "%s %s \n ", taskName,
             "terminated prematurely due to interruption");
        }// end catch
        catch ( FileNotFoundException filenotfound )
            System.out.printf (" %s %s \n ", filenotfound,
              "File not found");
        catch (IOException ioexception)
          System.err.printf(
            "Unable to read file");
        // close file and terminate application
       public void closeFile()
             input.close();
          }// close file
              output.close();
       } // end method closeFile
    }

    FRiveraJr wrote:
    Hi jverd
    What are you having trouble with?
    I know how to use the BufferedReader and BufferedWriter for opening, reading and writing to file. But the trouble consists in a lot of code to write and how will I call the appropriate file name since it is supposed to be
    the same name as the thread into all of this? I still don't know what problem you're having.
    You know how to provide a file name, right?
    Do you know how to get a thread name?
    If both are "yes", then I don't see what's left that you'd be having problems with. You need to be specific. Nobody here can read your mind, since it's the holidays.
    Writing to a file?
    Yes, I'm getting the correct results to the console with the thread name and the calendar option with the date and time and this is the data that needs to be written to a file. Isn't there a more simple way?A simpler way than your current code? How can anybody answer that without seeing your code?
    What would I need to do to write the same information 1000 times to the file?
    Because that is part of the requirements. Is not that I am insane :0).... This is just part of developing my skills since I'm new to all this. So, do you still have a question about this part? You do know how to loop, right? If not, you shouldn't be getting anywhere near I/O or multithreading.

  • File Based Multithreaded Web Server Question

    Hi friends,
    I have the code of a simple File Based Multithreaded Web Server. I have been asked to add proper http/1.1 Keep-Alive behavior to it. As far as I understand it means to use the same socket for the request coming from the same client without opening a new socket for every request by it. I am unable to implement it. Any help would be greatly appreciated. The entire code is as below:
    package multithreadedwebserver.com;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    /** This Class declares the general and HTTP constants
    * and defines general static methods:
    class Constants {
    /** 2XX: generally "OK" */
    public static final int HTTP_OK = 200;
    public static final int HTTP_CREATED = 201;
    public static final int HTTP_ACCEPTED = 202;
    public static final int HTTP_NOT_AUTHORITATIVE = 203;
    public static final int HTTP_NO_CONTENT = 204;
    public static final int HTTP_RESET = 205;
    public static final int HTTP_PARTIAL = 206;
    /** 3XX: relocation/redirect */
    public static final int HTTP_MULT_CHOICE = 300;
    public static final int HTTP_MOVED_PERM = 301;
    public static final int HTTP_MOVED_TEMP = 302;
    public static final int HTTP_SEE_OTHER = 303;
    public static final int HTTP_NOT_MODIFIED = 304;
    public static final int HTTP_USE_PROXY = 305;
    /** 4XX: client error */
    public static final int HTTP_BAD_REQUEST = 400;
    public static final int HTTP_UNAUTHORIZED = 401;
    public static final int HTTP_PAYMENT_REQUIRED = 402;
    public static final int HTTP_FORBIDDEN = 403;
    public static final int HTTP_NOT_FOUND = 404;
    public static final int HTTP_BAD_METHOD = 405;
    public static final int HTTP_NOT_ACCEPTABLE = 406;
    public static final int HTTP_PROXY_AUTH = 407;
    public static final int HTTP_CLIENT_TIMEOUT = 408;
    public static final int HTTP_CONFLICT = 409;
    public static final int HTTP_GONE = 410;
    public static final int HTTP_LENGTH_REQUIRED = 411;
    public static final int HTTP_PRECON_FAILED = 412;
    public static final int HTTP_ENTITY_TOO_LARGE = 413;
    public static final int HTTP_REQ_TOO_LONG = 414;
    public static final int HTTP_UNSUPPORTED_TYPE = 415;
    /** 5XX: server error */
    public static final int HTTP_SERVER_ERROR = 500;
    public static final int HTTP_INTERNAL_ERROR = 501;
    public static final int HTTP_BAD_GATEWAY = 502;
    public static final int HTTP_UNAVAILABLE = 503;
    public static final int HTTP_GATEWAY_TIMEOUT = 504;
    public static final int HTTP_VERSION = 505;
    /* the Web server's virtual root directory */
    public static File root;
    static PrintStream log = null;
    /* Configuration information of the Web server is present
    * in this props object
    protected static Properties props = new Properties();
    /* timeout on client connections */
    static int timeout = 0;
    /* maximum number of worker threads */
    static int workerThreads = 5;
    /* General method for printing strings */
    static void printString(String s) {
    System.out.println(s);
    /* print logs to the log file */
    static void log(String s) {
    synchronized (log) {
    log.println(s);
    log.flush();
    /* print to the log file */
    static void printProperties() { 
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Web server's virtual root directory= "+root);
    printString("Timeout on client connections in milliseconds= "+timeout);
    printString("Number of Worker Threads= "+workerThreads);
    printString("\n");
    printString("#####################################################################");
    printString("\n\n");
    printString("********************WEBSERVER STARTED SUCCESSFULLY********************\n");
    /* load server.properties from java.home */
    static void loadServerConfigurationProperties() throws IOException {
    File f = new File(System.getProperty("java.home")+"\\lib\\"+"server.properties");
    if (f.exists()) {
    InputStream is =new BufferedInputStream(new FileInputStream(f));
    props.load(is);
    is.close();
    String r = props.getProperty("root");
    if (r != null) {
    root = new File(r);
    if (!root.exists()) {
    throw new Error(root + " Server Root Directory does not exist");
    r = props.getProperty("timeout");
    if (r != null) {
    timeout = Integer.parseInt(r);
    r = props.getProperty("workerThreads");
    if (r != null) {
    workerThreads = Integer.parseInt(r);
    r = props.getProperty("log");
    if (r != null) {
    log = new PrintStream(new BufferedOutputStream(
    new FileOutputStream(r)));
    /* Assign default values to root, timeout,
    * workerThreads and log if the same have
    * not been specified in the server.propwerties file
    if (root == null) {   
    root = new File(System.getProperty("user.dir"));
    if (timeout <= 1000) {
    timeout = 5000;
    if (workerThreads > 25) {
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Too many Threads!!!Maximum number of Worker Threads can be 15 only");
    printString("\n");
    printString("#####################################################################");
    workerThreads = 15;
    if (log == null) {
    log = System.out;
    public class WebServer extends Constants {
    /* Specifying Default port for listening the requests */
    static int port = 8080;
    /* The Vector class implements a growable array of objects.
    * Like an array, it contains components that can be accessed using an integer index.
    * The size of a Vector can grow or shrink as needed to accommodate adding and
    * removing items after the Vector has been created.
    * The workerThreads are added to the Vector object threads where the worker threads stand idle
    * Vector is used since it is synchronized
    static Vector threads = new Vector();
    public static void main(String[] userSpecifiedPort) throws Exception {
    if (userSpecifiedPort.length > 0) {
    port = Integer.parseInt(userSpecifiedPort[0]);
    loadServerConfigurationProperties();
    printProperties();
    /* Instantiate ThreadPoool class and call
    * the createThreadPool() method on threadPool object
    ThreadPool threadPool= new ThreadPool();
    threadPool.createThreadPool();
    /* This class implements java.lang.Runnable.
    * It runs in a worker thread to process the request and serve files to the clients.
    class Worker extends WebServer implements Runnable {
    static final byte[] EOL = {(byte)'\r', (byte)'\n' };
    final static int BUFFER_SIZE = 2048;
    /* A byte array buffer to read and write files.
    * Memory is allocated to it once in the construtor of the class Worker
    * and reused thereafter
    byte[] buffer;
    /* Socket for the client being handled */
    private Socket socket;
    Worker() {
    buffer = new byte[BUFFER_SIZE];
    socket = null;
    synchronized void setSocket(Socket socket) {
    this.socket = socket;
    notify();
    public synchronized void run() {
    do {
    if (socket == null) {
    /* Wait */
    try {
    wait();
    } catch (InterruptedException e) {
    continue;
    try {
    handleClientRequest();
    } catch (Exception e) {
    e.printStackTrace();
    socket = null;
    Vector pool = WebServer.threads;
    synchronized (pool) {
    /* When the request is complete add the worker thread back
    * into the pool
    pool.addElement(this);
    }while(true);
    void handleClientRequest() throws IOException {
    InputStream is = new BufferedInputStream(socket.getInputStream());
    PrintStream ps = new PrintStream(socket.getOutputStream());
    /* we will only block in read for this many milliseconds
    * before we fail with java.io.InterruptedIOException,
    * at which point we will abandon the connection.
    socket.setSoTimeout(WebServer.timeout);
    socket.setTcpNoDelay(true);
    /* Refresh the buffer from last time */
    for (int i = 0; i < BUFFER_SIZE; i++) {
    buffer[i] = 0;
    try {
    /* We will only support HTTP GET/HEAD */
    int readBuffer = 0, r = 0;
    boolean endOfLine=false;
    while (readBuffer < BUFFER_SIZE) {
    r = is.read(buffer, readBuffer, BUFFER_SIZE - readBuffer);
    if (r == -1) {
    /* EOF */
    return;
    int i = readBuffer;
    readBuffer += r;
    for (; i < readBuffer; i++) {
    if (buffer[i] == (byte)'\n' || buffer[i] == (byte)'\r') {
    /* read one line */
    endOfLine=true;
    break;
    if (endOfLine)
    break;
    /*Checking for a GET or a HEAD */
    boolean doingGet;
    /* beginning of file name */
    int index;
    if (buffer[0] == (byte)'G' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'T' &&
    buffer[3] == (byte)' ') {
    doingGet = true;
    index = 4;
    } else if (buffer[0] == (byte)'H' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'A' &&
    buffer[3] == (byte)'D' &&
    buffer[4] == (byte)' ') {
    doingGet = false;
    index = 5;
    } else {
    /* This method is not supported */
    ps.print("HTTP/1.0 " + HTTP_BAD_METHOD +
    " unsupported method type: ");
    ps.write(buffer, 0, 5);
    ps.write(EOL);
    ps.flush();
    socket.close();
    return;
    int i = 0;
    /* find the file name, from:
    * GET /ATG/DAS6.3.0/J2EE-AppClients/index.html HTTP/1.0
    * extract "/ATG/DAS6.3.0/J2EE-AppClients/index.html "
    for (i = index; i < readBuffer; i++) {
    if (buffer[i] == (byte)' ') {
    break;
    String filename = (new String(buffer, 0, index,
    i-index)).replace('/', File.separatorChar);
    if (filename.startsWith(File.separator)) {
    filename = filename.substring(1);
    File targ = new File(WebServer.root, filename);
    if (targ.isDirectory()) {
    File ind = new File(targ, "index.html");
    if (ind.exists()) {
    targ = ind;
    boolean fileFound = printHeaders(targ, ps);
    if (doingGet) {
    if (fileFound) {
    sendResponseFile(targ, ps);
    } else {
    fileNotFound(targ, ps);
    } finally {  
    // socket.close();
    System.out.println("Connection Close nahi kiya");
    boolean printHeaders(File targ, PrintStream ps) throws IOException {
    boolean ret = false;
    int responseStatusCode = 0;
    if (!targ.exists()) {
    responseStatusCode = HTTP_NOT_FOUND;
    ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found");
    ps.write(EOL);
    ret = false;
    } else {
    responseStatusCode = HTTP_OK;
    ps.print("HTTP/1.0 " + HTTP_OK+" OK");
    ps.write(EOL);
    ret = true;
    log("From " socket.getInetAddress().getHostAddress()": GET " +
    targ.getAbsolutePath()+"-->"+responseStatusCode);
    ps.print("Server: Simple java");
    ps.write(EOL);
    ps.print("Date: " + (new Date()));
    ps.write(EOL);
    if (ret) {
    if (!targ.isDirectory()) {
    ps.print("Content-length: "+targ.length());
    ps.write(EOL);
    ps.print("Last Modified: " + (new
    Date(targ.lastModified())));
    ps.write(EOL);
    String name = targ.getName();
    int ind = name.lastIndexOf('.');
    String ct = null;
    if (ind > 0) {
    ct = (String) map.get(name.substring(ind));
    if (ct == null) {
    ct = "unknown/unknown";
    ps.print("Content-type: " + ct);
    ps.write(EOL);
    } else {
    ps.print("Content-type: text/html");
    ps.write(EOL);
    return ret;
    void fileNotFound(File targ, PrintStream ps) throws IOException {
    ps.write(EOL);
    ps.write(EOL);
    ps.println("The requested file could not be found.\n");
    void sendResponseFile(File targ, PrintStream ps) throws IOException {
    InputStream is = null;
    ps.write(EOL);
    if (targ.isDirectory()) { ;
    listDirectory(targ, ps);
    return;
    } else {
    is = new FileInputStream(targ.getAbsolutePath());
    try {
    int n;
    while ((n = is.read(buffer)) > 0) {
    ps.write(buffer, 0, n);
    } finally {
    is.close();
    /* mapping file extensions to content-types */
    static java.util.Hashtable map = new java.util.Hashtable();
    void listDirectory(File dir, PrintStream ps) throws IOException {
    ps.println("<TITLE>Multithreaded Webserver</TITLE><P>");
    ps.println("<html><body align=center>");
    ps.println("<center><h3><font color=#9999CC>Simple File Based MultiThreaded WebServer</font></h3></center>");
    ps.println("<table border=1 align=center>");
    ps.println("<tr bgcolor=#9999CC><td width=100% height=100% align=center><h3>Directory Listing</h3></td>");
    ps.println("<td width=40% height=40% align=center><h3>Type</h3></td>");
    String[] list = dir.list();
    for (int i = 0; list != null && i < list.length; i++) {
    File f = new File(dir, list);
    if (f.isDirectory()) {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\"face=\""+"Verdana"+"\"> <A HREF=\""+list[i]+"/\">"+list[i]+"</A></font><a href=\""+list[i]+"/\"></a>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/folder.jpg"+"\"></img></a>");
    ps.println("</td");
    ps.println("</tr>");
    } else {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\" face=\""+"Verdana"+"\"></A> <A HREF=\""+list[i]+"\">"+list[i]+"</A></font><A HREF=\""+list[i]+"\"></A>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/file.gif"+"\"></img></a>");
    ps.println("</tr>");
    ps.println("</table>");
    ps.println("<P><HR><I><font color=blue>"+(new Date())+"</font></I>");
    ps.println("<I><font color=blue>Copyright to HCL Technology Ltd</font></I>");
    ps.println("<I><font color=blue>Author Vivek Kumar Sinha</font></I>");
    ps.println("</body></html>");
    The ThreadPool class contains a Vector of WorkerThread objects.
    These objects are the individual threads that make up the pool.
    The WorkerThread objects will start at the time of their construction.
    If there are more HTTP requests than there are WorkerThreads,
    the extra requests will backlog until WorkerThreads free up.
    class ThreadPool extends WebServer{
    void createThreadPool(){
    for (int i = 1; i <= workerThreads; ++i) {
    Worker w = new Worker();
    Thread t=new Thread(w, "Worker Thread No."+i);
    t.start();
    /* Uncomment to check the number of worker threads running */
    // printString("Worker Thread No."+i+" Started");
    threads.addElement(w);
    try{
    ServerSocket serversocket = new ServerSocket(port);
    do {
    Socket socket = serversocket.accept();
    Worker w = null;
    synchronized (threads) {
    if (threads.isEmpty()) {
    /* Do nothing */
    } else {
    w = (Worker) threads.elementAt(0);
    threads.removeElementAt(0);
    w.setSocket(socket);
    } while (true);
    } catch (IOException e) {
    e.printStackTrace();

    Thank you for Welcoming me!!! I am very new to this forum so din't have this idea.
    I am unable to add the keep alive behavior . I don't have problem with any part of the code. The problem is i don't know how to make that enhancement in the existing code.
    Regards

  • Query on using Collection object in Multithreading

    All,
    I have a query on multithreading, I have a collection object-eg. HashMap which needs to be shared
    among threads, I my have 3 options
    1st option is to synchronize the method which does some manipulation on the collection object,
    2nd option is to hold a lock on that object like
    synchronized(object){
    //do some work
    3rd option - to make use of class ConcurrentHashMap available in java.util.concurrent package; which claims to be
    Thread safe but also says the following in the API - They do not throw ConcurrentModificationException. However,
    iterators are designed to be used by only one thread at a time
    My queston is - how do I choose between these 3?
    I know the decison needs to be taken by keeping performance issue in mind and also the number of times the values in HashMap will be updated by the threads. Can some one explain to me when/under what circumstances do I use options 1 || 2 || 3

    My application has actually gone live now - after doing some load/performance testing
    and comming to the conclusion that performance is satisfactory [I am designing a SMS gateway
    that receives/buffers/stores/sends SMS]
    Initially I used Hashmap and a LinkedList to store objects in memory and I had a mixture
    of places where some times I made the entire method that modifies the LinkedList & hashmap
    synchronized and some places where I held a lock on the object alone (I wasnt too sure which to use where)
    Then upon movin to 1.5 I rechanged the the data structure to use ConcurrentLinkedQueue & ConcurrenthashMap.
    But i have places where I still hold synchronized locks over those objects (which i think is unnecessary and removing the locks may improve the performance)
    So can i come to the conclusion that classes in java.util.concurrent are all threadsafe and we can stop holding locks on the objects and let java take care of itself [or should I still hold a lock when doing structural modification] [though the APi states that a oncurrentmodificationexception will not be thrown & iterators are designed to be used by only one thread at a time]

  • Using time() function in multithreaded application

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

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

  • Multithreading issue on Solaris 8 branded zone

    Hi,
    We are facing a multithreading problem in Solaris 8 container (branded zone) on Solaris 10.
    The core file shows 2 LWPs for a single thread.
    First LWP
    (dbx) lwp
    current LWP ($lwp) is l@1403
    (dbx) print this->m_ThreadId->m_IdImpl.m_PosixId
    this->m_ThreadId.m_IdImpl.m_PosixId = 1404U
    Second LWP
    (dbx) lwp
    current LWP ($lwp) is l@1404
    (dbx) print this->m_ThreadId->m_IdImpl.m_PosixId
    this->m_ThreadId.m_IdImpl.m_PosixId = 1404U
    Another point to note is that dbx returns 'MT support is disabled' for this program even though it has been built using the -mt option. The dbx version is Sun Dbx Debugger 7.5 2005/10/13.
    As far as I have read, the Solaris 8 branded zone uses the alternate T2 thread library. Note also that this program is linked with the alternate thread library @ /usr/lib/lwp.
    This alternate thread library is supposed to use the 1:1 thread model.
    Can someone explain why are we then seeing 2 LWPs for a single thread ?
    Thanks,
    Best regards,
    Raj Iyer

    This error messages are output by
    cssd which is a input method of Japanese.
    If you don't use Japanese input method cs00, you can stop it by following method.
    # /etc/init.d/loc.ja.cssd stop
    # mv /etc/rc2.d/S90loc.ja.cssd /etc/rc2.d/_S90loc.ja.cssd

  • Urgent!!!!! Please Help.. Multithreading!

    Hello,
    I have written a client-server application which is a sort of a chat program. The server has to be multithreaded as it has to service any number of clients. Further the server has to keep track of the users connected to it and send this list to the clients. I have written code for a single threaded server but i'm new to multithreading. Can anyone help me with the code please. Its very urgent.
    Any help appreciated.
    Thanks and regards.

    Oh NO! I was too busy answering a post which was SUPER URGENT!!!!!! (It had 6 exclamation points and yours only has 5, plus it said SUPER). MAN, I hope you didn't DIE or something...

  • Question related to multithreaded support in X-Fi driv

    Are there any plans for multithreaded support in X-Fi drivers?IF yes, when and for what OSes ?thanks for answers

    This is a limitation of the card's hardware. No software driver will fix it.

  • Is this multithreading...or not?

    Hi, I made a program in my intention multithreading but I'm not really sure it really is so I ask to you.
    I made a class with some basic operations on a data structure:
    public class operationalClass{
         Astructure dataStructure;
         public void operation1(int value){
              dataStructure.insertValue(value);
        public int operation2(){
             return dataStructure.getValue();
    }dataStructure has already internal mechanisms to handle concurrency.
    Now, if I make several threads (likely producer/consumer) which will call operationalClass methods will these operations be executed in concurrency?(i.e. while dataStructure.insertValue() method is still operating, a thread can call operationalClass.operation1/operation2?).
    Obviously threads will deal with the same operationalClass object.

    Squall867 wrote:
    Hi, I made a program in my intention multithreading but I'm not really sure it really is so I ask to you.
    I made a class with some basic operations on a data structure:Please, follow Java coding conventions when you write Java code. A class name should start with an uppercase character.
    >
    public class operationalClass{
    }dataStructure has already internal mechanisms to handle concurrency.What mechanisms?
    Now, if I make several threads (likely producer/consumer) which will call operationalClass methods will these operations be executed in concurrency?(i.e. while dataStructure.insertValue() method is still operating, a thread can call operationalClass.operation1/operation2?).Depends on your implementation of the methods.

  • Does Adobe Flex 4.6 SDK supports multithreading?

    Hi,
    As we are using Adobe Flex 4.6 sdk for our vmware vcenter plug-in development. we need to handle the situations like updating the data in multiple panels and portlets of a dashboard simultaneously.
    So we are thinking to implement this using multithreading concept.
    I am hearing flex doesn't support multi-threading, some workers constructors will give flavor of the multi-threading in flex.
    It will be helpful if you provide some information about
    1. Does Adobe Flex 4.6 SDK supports multithreading? If so how to implement?
    2. How to use Workers in flex and what are the limitations?
    Thanks and Regards,
    Sravan Kumar.

    https://forums.adobe.com/message/4562551

  • Multithreaded Java app calling C via JNI...need help!

    I have a multithreaded Java app making a JNI call into some C code. It is a high speed imaging algorithm that I simply can't/don't want to do in Java. I am very new to JNI and I am hoping to get some expert advice on how to solve this issue. Basically, I need a seperate JNI session (if that is such a thing) per thread. In other words, I need to essentially keep state of each JNI call as it pertains to the current thread.
    The 2 ideas I have thought about are:
    1. Have the native code pass the data back into java, and have the java object hold it. Then, when subsequent native calls are made, you pass the data as a paramter of the native method.
    (This can be painful as it a lot of complicated and/or a lot of data.)
    2. Define some sort of a structure to hold each instance of the data on the C side, returning to java a lookup key. Subsequent native calls include the key as a paramter, and the data is looked up. ( a quick example of this would be nice).
    I would appreciate any information/expereince/pains with this one.
    Thanks!

    2. Define some sort of a structure to hold each instance of the data on the C side, returning to java a lookup key. Subsequent native calls include the key as a paramter, and the data is looked up. ( a quick example of this would be nice).The lookup key, or a simple "pointer", can be returned to Java as a plain old "int" or "long" (I don't know what is the size of the pointers in your platform, if 32 or 64-bit). So you can return a "long", that can be treated by Java programs as an "opaque handle" (a pompous name for things that can't be handled adequately at the "client" side).
    I assume that C/C++ allocates the memory and it remains "fixed" (untouched by garbage collection) between calls. So a real C pointer can be used in such case. If you have some smarter scheme of allocating things in your program, return another kind of lookup key (for instance, if you allocate things in fixed-size C arrays, you can return the index of the C object in the array instead of returning a plain pointer.

  • How to Use Images in Multithreading

    Actually I have an image application which we can drag and drop the images.
    I need some more help to do more.
    If drag and drop more than 3 images, it will take more than time to display all the images. So I was trying to use multithreading to display the images one by one, but I am not able implement it.
    anybody can help me.

    I answered this in the GUI forum

  • Unzip files from a folder which is updating regularly using multithreading

    Hi All,
    I have acode which unzip all the files from a folder .This code picks up all the zipped files at a time and then unzip it and write them to another folder but now my requirement is changed ,suppose the source folder where all the zipped files are present is refreshed or updated with new zipped files regularly then how can I implement in my code multithreading to get several files by threads and send it for unzipping.
    Please suggest with some example or edit my code.
    package com.myprojcet;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    public class Main {
         * Extracts a zip file
         public void extractZipFile() {
              try {
                   String zipFileName = "C:\\soft\\test"; //Source folder for zipped files
                   //Create input and output streams
                   File SourceDir = new File(zipFileName);
                   File[] zipFiles = SourceDir.listFiles();
                   ZipInputStream inStream = null;
                   OutputStream outStream = null;
                   ZipEntry entry;
                   byte[] buffer = new byte[1024];
                   int nrBytesRead;
                   //Get next zip entry and start reading data
              for(int i=0; i < zipFiles.length; i++) {
                   inStream= new ZipInputStream(new FileInputStream(zipFiles));
                   while((entry = inStream.getNextEntry()) != null) {
                        outStream=new FileOutputStream("C:\\soft\\test2\\"+entry.toString()); //destination folder for unzipped file
                        while ((nrBytesRead = inStream.read(buffer)) > 0) {     
                             outStream.write(buffer, 0, nrBytesRead);
                   //Finish off by closing the streams
                   outStream.close();
                   inStream.close();
              } catch (IOException ex) {
                   ex.printStackTrace();
         * @param args the command line arguments
         public static void main(String[] args) {
              new Main().extractZipFile();
    Thanks
    Sumit
    Edited by: user8687839 on Feb 27, 2012 11:00 PM

    But my question is that if in a source folder we have several files which are in zipped format and the folder is getting updated every min (say) with new zipped files (which are dumped from some outside environment).I need to unzip all the files present in the folder ,if new one comes there then also check for the new zipped file and unzip it.You don't need to keep re-stating that.
    I had written a code for unzipping a file from a folder (thinking the folder is not updated everytime).Or that.
    Now I am thinking of using threads because if I create suppose 5 threads and every threads poll the source folder and pick up a zip file ,send it for unzipping it and again poll the source folder for any new entries?Or that.
    If using the threads here hits performace then what should I use?Err, what you presently have?
    Provide me any sample code or link that would be more useful.You've already written it.

Maybe you are looking for

  • Automatic PO creation from SC

    Hi Experts, I am using SRM 7.0 with extended classic scenario and I have issue in the automatic po creation. For some Shopping Carts the PO is not automatically created. The SC is having Source of Supply Assigned and all the approves have completely

  • Project Server 2010 - A project blocks My tasks

    Hello! I am currently unable to open My Tasks page. Here's the short history. We're preparing a presentation with screenshots of various pages on PS2010, and for some reason, a colleague has decided to assign about 250 tasks - almost a whole project

  • Messages are in Backlog without any status

    Hi All, Today morning when I came and observed that, in the Engine-Status page i saw some 3000 messages under column "Processing Backlog (without errors)". When I went into Messaging Overview Tab, I see these messages are in 'To Be Delivered' status.

  • Unwanted blank bookmark icons

    i have 5pages of empty bookmarks on my iphone 4s that no matter how many times i delete within a few hours they come back and its really anoying that i cant get them to go permantly! Please help

  • Time Capsue 1GB + MobileMe: I guess I dont 'get it'

    I've poked around and I think being new to Mac and the Time Capsule [not to mention MobileMe] I am a little confused. I purchased the Time Capsule for doing backups, and then found it would integrate with my MobileMe account - great! My impression of