MultiThread Syncronisation
Hi,
This is my Thraed program and the output of this program is given below. Can anyone tell how it gave that output? I understand it is syncronisation problem, but trying to understand how it gave that output.
public class TestThread implements Runnable {
public static int x = 0;
public void run() {
x = x 1;
FileOutputStream fOut = new FileOutputStream("c:/data1.txt", true);
fOut.write(("Before : x = " x " " "bookingNumber").getBytes());
fOut.flush();
fOut.close();
public void static void main(String [] args) {
Thread thread = new Thread(new TestThread());
thread.start();
thread = new Thread(new TestThread());
thread.start();
thread = new Thread(new TestThread());
thread.start();
CONTENTS OF c:/data1.txt:
Before : x = 1 bookingNumberBefore : x = 1 bookingNumberBefore : x = 2 bookingNumber
w Thread(new TestThread());
thread.start();
thread = new Thread(new TestThread());
thread.start();
CONTENTS OF c:/data1.txt:
Before : x = 1 bookingNumberBefore : x = 1 bookingNumberBefore : x = 2 bookingNumber
Simple synchronization problem, because:
x = x + 1
is getting executed simultaneously (that is, almost simultaneously) by multiple threads, and it is not an "atomic" operation. Thread 1 will get the value of x (0) and start to add 1 to it, while Thread 2 will get the value of x (which is still 0) and start to add 1 to it. Then thread 1 saves the new value into x (now 1), and thread 2 saves the new value into x (which it calculated as 1 as well).
Similar Messages
-
JNI Multithreading/Callback Function Design Issues
Ok, I have been working on this for quite some time now and I simply can not figure it out. So any ideas are more than welcome. :)
I have Java code that uses a DLL that I created in C++. My C++ code links with a library made by a 3rd party (don't have access to the source or anything). The 3rd party's code creates a new thread and calls a callback function that I define in my C++ code. This callback is called continuously until I perform some other code to stop it. Now for the tricky part. In my callback function I need to pass some data back in Java. Here is where my design falls apart. Since the callback function is technically part of the 3rd party's thread, I have to call AttachCurrentThread() in the callback to get the JNIEnv pointer in order to ultimately call my desired Java method. The problem is that my Java method (or even the C++ callback function) are only invoked if I do a sleep() in my C++ code after I start the 3rd party code which creates the thread. If I do a Thread.sleep() in Java after I call the native function code, it just sleeps and the callbacks never get called. It appears as though the thread dies as soon as I return from my C++ code.
So now I am stuck. I have tried creating a thread in Java which simply calls the C++ code and the C++ code just loops waiting for an updated flag, however, this causes the 3rd party's thread creation code to fail (not quite sure why). However, even if their code worked, I'm not convinced this is even proper design. I apologize if this is simply a threading design principle as my multithreading programming techniques are a bit rusty and I've never done a multithreaded application this complex (this is a simplified version, but the idea is the same).
I welcome any suggestions or even documentation that may lead me in the right direction. Thanks in advance.I have a similar issue.
from java I call a dll I wrote, which calls a third party scanner dll (cyber.dll). Everything works ok, except, when an event in the scanner occurs, it calls the call backin my dll, which calls the callback in java, which kills the vm with an access violation. If I execute the call back to java from a c method which I just called from java, it works, but if it gets called outside of the java execution of the native code, it fails.
I havent done anything with treads or syncronisation. Do I need to do this AttachCurrentThread stuff? If so, where do I get the _jvm handle as Im not starting the vm from c? -
Transactions in Multithreaded app
Is it safe to use the same java.sql.Connection instance all over multithreaded app? Is transaction session associated with a thread? Or one Connection keeps just one transaction session for all threads?
Any help's appreciated.Is it safe to use the same java.sql.Connection
instance all over multithreaded app?Yes, providing your access/uses is thread safe, i.e. syncronised.
Is transaction
session associated with a thread?No a connection.
Or one Connection
keeps just one transaction session for all threads?Yes.
A transactions should be autonomous, if all threads use the same transaction, it would be pointless using transactions in the first place.
Any help's appreciated.Checkout these link, your should
http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/bmp.html
http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/jdbc.html
http://developer.java.sun.com/developer/technicalArticles/xml/metadata/ -
Syncronising is creating a new folder in Outlook w...
I have just got a N70 phone and syncronised fine a few times with Microsoft Outlook. All of a sudden i realised that when i syncronised again the phone created a new folder in Microsoft Outlook which I cannot access and cannot delete. As it is called the same as my actual calendar when I go to syncronise again the syn gets confused and doen't do it, getting error report in PC Suite. I tried posinting it to the right folder but it still gets confused!
I spent a few hours with a very nice person who handles my email accounts to create a new mail account to get rid of the new folder. As soon as we finally managed to get rid of these corrupt folders I syncrnised and they appered in the new account again!
Really not sure what to do now!I forgot to mention that I downloaded the latest version of PC Suite off your website and that the connection is via USB Cable
-
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 -
How do i syncronise two macs on the same network
I currently have a macbook pro, and that is now going to be my home office computer. I am about to buy a macbook air as my travel laptop. I will need them to have the same information on how do I keep them syncronised when I update information on one or the other.
How to Keep Two Macs in Sync
osx - How to keep two Macs in sync?
syncing two macs: what will work...:
Synchronizing two Macs using an Intermediary
Sync several Macs: sync Macs with Mac OS X sync tool SyncMate
Best Sync app for two macs? -
How can I recover a purchased app on one itouch (which has since died) and put it on my new itouch device if I haven't syncronised my old device with my mac/itunes account before it died?
It is easy to download items you have purchased from iTunes again; this article will walk you through it: http://support.apple.com/kb/HT2519
You want the "Apps on iOS" section. -
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. -
Syncronising address book and Calander between macs
Hi
I have Mini Mac (Tiger), Macbook (Leapord) and Airport express. I want to keep the address book and calander syncronised automatically.
I do not have mobile me. I mainly use google mail.
Does isync help of howelse do I do it?
BadrakumarNo, iSync is for syncing Contacts and Calendars to third-party mobile phones and PDAs. It does not sync anything between Macs.
Apple's MobileMe is for syncing Address Book and Calendars between multiple Macs.
You might also be able to use Google's new CalDAV feature:
http://www.google.com/support/calendar/bin/answer.py?answer=99355&topic=13949
Or SpanningSync:
http://www.macupdate.com/info.php/id/24117/spanning-sync
Or BusySync:
http://www.macupdate.com/info.php/id/25922/busysync -
My account was deleted for security issues. I made a new account, but I can't syncronise my apps with this new account. I bought a new Iphone and would like to transfer the apps ans music on this new one. Can somebody help me?
Why would you make a new account? This will likely cause many problems. Just get you old account enabled.
Apple ID: "This Apple ID has been disabled for security reasons" alert appears
Frequently Asked Questions About Apple ID
Everything you purchased with the old account will always be tied to that account. You will have to authorize the computer for that account and you will have to update the apps from that account. -
After formatting the partition and installing Firefox again, I wanted to get my settings, bookmarks etc. back by syncronising with Firefox Sync but accidentaly settings from a fresh browser was uploaded and now I cannot have the browser the way I used to have. Is there any way to reverse this changes?
Hi zoomy,
First check that you still have data in your sync account.
Firefox button > Options > Sync > Manage Account
It should tell you how much data is stored in the account. Is there any?
If there is still data in the sync account then you can follow the instructions in this article [[What is Firefox Sync?]]. Refer to the 'How much of my data is synced?' section. Change the option to 'Replace all data on this computer with my Sync data'.
I hope that works for you.
If there is no data in your sync account you will be able to get it back by syncing from another computer. Just make sure that the settings on that computer are not replaced by the blank account again. You can use the 'Replace all other devices with this computer's data' option to prevent this.
Please note that Firefox Sync is designed only to sync details between devices not as an online backup tool. If you are formatting a partition it is generally best to backup your profile folder along with any other data. See [[Managing profiles]] for more detail.
--Edward -
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 || 3My 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]
Maybe you are looking for
-
Can't find any of my HD Video on a PC external drive
Just got my new MacBook aluminum ten days ago as my first Mac. I have a Maxtor Onetouch 300G external hard drive that has hours upon hours of HD video shot with a Sony handicam and imported and saved to the Maxtor through my old PC laptop. I plugged
-
Hi my iphone 4s still has pictures on it from my old computer. I recently put my itunes on a new computer and the old photos albums can not be deleted off my iphone. It is taking up too much room and I want them off. How do i get rid of them if they
-
CANopen communication over TCP/IP
The NI Modbus Library makes it possible to implement the MODBUS protocol through COMPORT or over the TCP/IP. I would like to implement the NI CAN or the NI CANopen communication through a COMPORT (VISA connection) or secondary through TCP. Can anyone
-
Are tasks or to-do's supported?
Are tasks or to-do's supported? <P> Yes, iCS 2.x supports tasks. They are available in all views. Tasks can be repeating or non-repeating.
-
PI JMS Adapter MQ Message Format
Hi, I know that if you change the target client in the JMS adapter properties il will change the message format for MQSTR (Websphere MQ Non-JMS) or MQRFH2 (JMS-Compliant). But is there a way to force the MQ Message format to NONE or an empty string?