MultiThread question

Hello I'm a new java programmer. I have a problem:
I have to create a thread of processes, say 5 threads.
but only 2 at time should execute. After one of those 2 finishes, then the next thread should be started, and so on.. until all the threads will be finished.
Is this possible? how am I gonna do this?

I you only need 2 threads running at a time, why don't you "reuse" a thread when it is done with a task.
And by reuse, I don't mean calling Thread.start again, because that won't work, but something like this:
public class TaskManager {
  class Task extends Thread {
    boolean running = true;
    public void kill() { running = false; }
    public void run() {
      while (running) {
        Runnable task = TaskManager.this.getTask();
        if (task == null)
          break;  // no more tasks to process
        task.run();
  private int index = 0;
  private Runnable[] tasks;
  public TaskManager() {
    // create tasks to be run:
    tasks = new Runnable[5];
    tasks[0] = new Runnable() {
      public void run() {
        int result;
        for (int i = 0; i < 10; i++)
          result += i;
        System.out.println(result);
    // and the next 4 tasks has to be created as well
    // start two threads
    Thread thread1 = new Task();
    Thread thread2 = new Task();
    thread1.start();
    thread2.start();
  public synchonized Runnable getTask() {
    if (index < tasks.size())
      return null;
    return tasks[index++]; // return the next task to the thread that called this method
}I think this will work, perhaps there are some bugs in it, but it gives you an idea.

Similar Messages

  • Singletons and multithreading question

    Hi, I had a class created as a singleton as it was only used in one place. However since Ive now multithreaded the part of the program that calls the singleton code so it could be called twice at the same time.
    If the method being called initializes all its variables within the method, is that method safe to be called in a mutli-threaded env or not ?
    If it in my situation all variables are declared within the method except a precompiled javax.xml.XPathExpression class, the same one is used to parse an Input Source, the input source itself is created within the method. I
    think I am having concurrency problems , (SAXParser Exceptions) and I think it is because of this XPathExpression class but cannot clearly understand why.
    What is the correct solution, I dont want to initilize the XPathExpression within the method because the method is called many times always for the same expression, dropping the singleton and creating new instances of the class on every call would be even worse. I require multithreading to improve concurrency is there a safe Multi Singleton pattern that i should be using ?

    There are two issues:
    a) is the singleton object safe for multithreaded use
    b) how do I safely create a singleton in a multi-threaded application
    The answer to (a) depends on the class. It sounds from your description that you are using an object (the XPathExpression) that might not be thread-safe. I can't tell you if it is or not. Assuming it is not you either need to synchronize this method so that all threads will go through it (and use the expression) one at a time - which may defeat the purpose of multi-threading - or else you need a way to use multiple instances of these expressions in different threads. As I'm not familiar with these classes I can't tell you what you can and can't do concurrently.
    There are a number of answers to (b). Construction via static initialization is the simplest and safest. If you want lazy initialization and the class that holds the reference to the singleton must be loaded even if the singleton isn't needed, then lookup the initialize-on-demand-holder-class idiom (see Josh Bloch's "Effective Java" item 48)

  • Multithread questions please take a look.

    if i am going to implement a client application to connect to a server, how many threads do i need?
    i need to have a thread for handling the UI.
    Question : threading for handling the UI for example a textArea if i have 2 textArea that changes its contents do i need 2 thread like 1 thread for textArea1 and another for textArea2?
    i need another thread for staying connected to the serverSocket and sending/recieving data to/from the server.
    Question : where do i call the network thread and the UI thread? both in the main()? or any other methods like calling network thread within UI thread etc?
    thanks alot
    i am new to thread and i have read the tutorial put up by java.sun.com by still unclear about it. please help
    thanks

    What you have to know about threads in Java is that they are as any other objects and you can treat them as such with the difference that the code in the run() method of that object is executed in a different context,so it appears that it is executed simultaniously with any other code in the application. The UI of a java application is executed in a thred which you dont have control over,it is hidden in the framework.In order to achieve flexible design a recommend you to define a class which extends java.lang.Thread and define a variable of the java.net.Socket class there.This class should be instantiated in the main application object.In the run() method implement the logic for reading from the socket,as it will always block if there is no data received. With approach like this you'll avoid UI freezing if you have a Socket object in the main class of the application and it blocks on the read method.
    The logic for data sending you can implement by adding methods in the class you defined which writes to the socket output stream. It is advisable that you implement some kind of notification mechanism from the thred object to the main application object that notifies when data has been received,so you can process it further and show it. Here is some small example:
    class MyApp implements DataReceivalNotificator{//the main class of the application
    private NetClient client;
    public MyApp(String host,int port){
    client = new NetClient(host,port);
    client.addDataReceivedNotificator(this);
    //start the thread;
    client.start();
    public static void main(String[] args){
    MyApp app = new MyApp(args[0],Integer.toString(args));
    app.sendData("Some data for the net:)");
    public synchronized void dataReceived(String data)
    //show the data somehow
    public void sendData(String s){
    client.sendSomeString(s);
    class NetClient extends Thread{
    private Socket soc;
    private DataInputStream inStream;
    private DataOutputStream outStream;
    private String someString;
    private DataReceivalNotificator notifier
    public NetClient(String host,int port){
    try{
    soc = new Socket(host,port);
    inStream = new DataInputStream(new BufferedInputStream(soc.getIputStream()));
    outStream = new DataOutputStream(new BufferedOutputStream(soc.getOutputStream()));
    catch(IOException e){
    public void run(){
    try{
    while(!(someString=outStream.readString()).equals(null)){
    //calls the notifiers method to receive the data
    notifier.dataReceived(someString);
    catch(IOException e){
    public synchronized void sendSomeString(String str){
    try{
    outStream.writeString(str);
    outStream.flush();
    catch(IOException e){
    public void addDataReceivalNotificator(DataReceivalNotificator d){
    notifier = d;
    public interface DataReceivalNotificator
    public void dataReceiver(String data);

  • Multithreading question

    Hi all,
    I know the default rule is to use the dispatch thread to perform gui-related job, but there are some exceptions as well.
    I have an application with several tabbed panes. Every tabbed pane shows some charts, which need to be updated even when the tabbed pane is not shown. Since updates come from remote hosts I need something non-blocking. Is it enough to use the SwingUtilities.invokeLater call (and thus using the event dispatch thread) or should I use something like this instead?
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;
    import javax.management.Notification;
    * The <code>Worker</code> class asynchronoulsy updates the {@link QCallback} object
    * associated to it. If a new event occurs while the thread is busy, it is
    * temporarily stored to a queue.
    final class Worker implements Runnable {
        // Instance fields
         * Queue holding all the notifications waiting to be processed.
        private BlockingQueue<Notification> eventQueue;
         * The callback object used to udpate the allocation charts.
        private QCallback callback;
         * Flag indicating this thread status.
        private volatile boolean running;
        // Constructor
         * Creates a new <tt>AllocationPanelUpdater</tt> object.
         * @param callback The callback object used to update the allocation charts.
        public Worker(QCallback callback) {
            this.callback = callback;
            this.eventQueue = new LinkedBlockingQueue<Notification>();
            this.running = true;
        // Methods
         * Stops this thread.
        public void stop() {
            running = false;
            Thread.currentThread().interrupt();
         * Stores the specified notification into the temporary buffer, waiting if
         * the buffer is full.
         * @param notification The notification.
         * @throws InterruptedException If interrupted while waiting.
        public void event(Notification notification)
                throws InterruptedException {
            this.eventQueue.put(notification);
        // --------------------------------------------------- Method from Runnable
         * @see java.lang.Runnable#run()
        public void run() {
            while (running) {
                try {
                    Notification n = this.eventQueue.take();
                    try {
                        if (n != null) {
                            this.callback.update(n);
                    } catch (Throwable e) {
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
    }   //  END WorkerAn example of QCallback object is:
    public class SchedulerPanel extends QAbstractPanel implements
            NotificationListener, QCallback, PropertyChangeListener {
         * The thread which updates the charts.
        protected final Worker worker;
         * The has map containing the historial allocation series for each pool
         * (including the scheduler pool).
        private ConcurrentMap<String, TimeSeries> historicalSeries;
    // other fields here
         * Creates a new <tt>SchedulerPanel</tt> object.
         * @param owner The parent component
        public SchedulerPanel(QTabbedPane owner) {
            super(owner, QTabbedPane.SCHEDULER);
            setToolTipText("Scheduler panel");
            this.historicalSeries = new ConcurrentHashMap<String, TimeSeries>();
            this.barChartDataset = new DefaultCategoryDataset();
            this.registeredNodesModel = new SetListModel<String>();
            this.barChartDataset = new DefaultCategoryDataset();
            this.worker = new Worker(this);
            QConsole.getThreadPool().execute(worker);
            // Add a vertical spacer that also guarantees us a minimum width:
            add(Box.createRigidArea(new Dimension(150, 10)));
            this.barChartPanel = new ChartPanel(createBarChart());
            fixPanelOptions(barChartPanel);
            add(barChartPanel, BorderLayout.NORTH);
            add(Box.createVerticalStrut(50)); // extra space
            add(createRegisteredNodesPanel());
            add(Box.createVerticalStrut(150)); // extra space
            TimeSeries schedulerHistorical = getConfiguredTimeseries();
            this.historicalSeries.put(SCHEDULER, schedulerHistorical);
            add(createHistoricalChart(SCHEDULER, schedulerHistorical));
            add(Box.createVerticalStrut(50)); // extra space
    // other methods here
       * Updates this <code>QCallback</code> object (potentially using a
       * different thread) with the data contained into the Notification.
       * @param notification The received notification.
    public void update(Notification notification) {
            final String type = notification.getType();
            if (NotificationType.NODE_ADDED.equals(type)) {
                // If a new node registers we only need to update the
                // relative jlist
                String node = (String) notification.getUserData();
                // this is a list model. All methods are synchronized
                registeredNodesModel.add(node);
            } else if (NotificationType.SERVICE_ADDED.equals(type)) {
                 * When a service added notification is received adds the scheduler
                 * pane to the notification listeners' list with the
                 * schedulerNotificationFilter enabled (so only some notifications
                 * will be delivered to the scheduler pane)
                ObjectName oname = (ObjectName) notification.getUserData();
                addBarChart(oname.getKeyProperty(ObjectNameUtil.QOSP_NAME));
                // Adds the service name to the list of available services
                // (right side of the window)
                owner.getOwner().getListPanel().add(oname);
            } else if (NotificationType.ALLOCATION.equals(type)) {
                allocation((NodeAllocationNotification) notification);
         * Creates a new bar element.
         * @param name The bar name.
         * @exception IllegalArgumentException If the name has already been used.
        protected final void addBarChart(String name)
                throws IllegalArgumentException {
            synchronized (this.barChartDataset) {
                if (this.barChartDataset.getColumnIndex(name) < 0) {
                    this.barChartDataset.addValue(0.d, ROW_KEY, name);
                } else {
                    // this.barChartDataset.setValue(0.d, ROW_KEY, name);
                    throw new IllegalArgumentException(
                            "The name is already contained into the chart");
            TimeSeries series = getConfiguredTimeseries();
            if (this.historicalSeries.putIfAbsent(name, series) != null) {
                throw new IllegalArgumentException(
                        "The name is already contained into the map!");
            add(createHistoricalChart(name, series));
            add(Box.createVerticalStrut(50)); // extra space
    }Will it work?
    Thanks,
    Michele

    Depending on how you setup your dataset I think that
    you can just update them and it will not refresh the
    gui.
    No, the dataset is a JFreeChart component.
    How/Where is the data stored for the charts? The data is stored into the dataset. Whith JFreeChart you inteact only with the dataset, not with the chart panel. The chart panel is added to the main panel/frame at the beginning. Then, if you want to update it you have to update the dataset.
    What if
    you keep it somewhere the you could update and not
    have change events be fired off? Then just grab the
    update to date data and repaint/rebuild the charts
    that are currently displayed.Please see above.
    What I think is that the access to the datasets is thread safe there shouldn't be problems. In fact the charts are panel components, so if a thread updates the dataset, it should be the same thread which updates the related chart. Does this make sense?

  • Design question for database connection in multithreaded socket-server

    Dear community,
    I am programming a multithreaded socket server. The server creates a new thread for each connection.
    The threads and several objects witch are instanced by each thread have to access database-connectivity. Therefore I implemented factory class which administer database connection in a pool. At this point I have a design question.
    How should I access the connections from the threads? There are two options:
    a) Should I implement in my server class a new method like "getDatabaseConnection" which calls the factory class and returns a pooled connection to the database? In this case each object has to know the server-object and have to call this method in order to get a database connection. That could become very complex as I have to safe a instance of the server object in each object ...
    b) Should I develop a static method in my factory class so that each thread could get a database connection by calling the static method of the factory?
    Thank you very much for your answer!
    Kind regards,
    Dak
    Message was edited by:
    dakger

    So your suggestion is to use a static method from a
    central class. But those static-methods are not realy
    object oriented, are they?There's only one static method, and that's getInstance
    If I use singleton pattern, I only create one
    instance of the database pooling class in order to
    cionfigure it (driver, access data to database and so
    on). The threads use than a static method of this
    class to get database connection?They use a static method to get the pool instance, getConnection is not static.
    Kaj

  • ESB listeners and multithread abilities questions

    Hello,
    A few simple questions.
    Is Oracle ESB mutlithreaded? Example, if I have 1 incoming file adapter, will the file adapter pick up 1 file at a time?
    Then let's say I have a routing process that transforms the file, and spits it out to an outbound file adapter. Is this transform piece multithreaded? Meaning is it going to transform 1 file at a time, or do as many as it can based on the amount of resources the box has?
    How about the outbound adapter? Same question, 1 at a time or as many as it can?
    Thanks.

    I believe it's 1 at a time, but it's in milliseconds so it appears that it's all at once.

  • Question about security context in multithreading environment

    I have a need to make concurrent calls to multiple EJBs in parallel threads. Let's
    say I establish the security context once by creating an InitialContext with given
    security principal and credential. With the security context active, I spawn multiple
    threads from the current thread and in each of those threads I make a call to
    a secure EJB method, which my security principal is allowed to access. My question
    is, will the same security context be established in each of the spawned thread
    so that my EJB calls succeed? For various reasons it's not feasible to login in
    each of the spawned threads, only to login once from the main thread.
    I tried this with WebLogic 6.1sp3 and it seems to work as expected. However, I
    have not been able to find any documentation on how security contexts are propagated
    to spawned threads. All I could find was a statement that when an InitialContext
    is created, the corresponding security context becomes associated with the current
    thread.
    My concern is that even though it works in WebLogic 6.1, it may no longer work
    the same way in WebLogic 7.0 or later. And will it work when the JNDI login mechanism
    is replaced by JAAS? If any WebLogic/security guru out there could give me some
    info on how WebLogic security contexts work in a multithreaded environment, I
    would be much obliged.
    Thanks in advance!
    Minh-Tue Vo

    "Minh-Tue Vo" <[email protected]> wrote in message
    news:[email protected]..
    >
    \> My concern is that even though it works in WebLogic 6.1, it may no longer
    work
    the same way in WebLogic 7.0 or later. And will it work when the JNDIlogin mechanism
    is replaced by JAAS? If any WebLogic/security guru out there could give mesome
    info on how WebLogic security contexts work in a multithreadedenvironment, I
    would be much obliged.
    With the JAAS model, you should be able to get a subject once and then do a
    runas in the spawned threads.

  • Question about static (+multithreading)

    Sample program for multithreading:
    cvidir\samples\utility\Threading\ThreadSafeVar\IncrementValue.prj
    Why all of global variables and functions are static ?
    regards
    Frog

    This is a CVI question and should be posted to the LabWindows/CVI forum instead. Static flags are used to tell the compiler that these global declarations are not used outside this code module (C file). It's good programming practice to declare global variables only used in one module as static.
    Best Regards,
    Chris Matthews
    National Instruments

  • 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

  • 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.

  • MultiThreaded compare and swap question.

    I'v got this assignment and I'm not sure which approach to take. I think I've got it right with my second try, but I was wondering if I could get some sort of verification or something.
    "Use Java monitors to implement the atomic Compare-And-Swap instruction, which has the following effect: CSW(a,b,c): < if (a==c) { c = b; return(0);} else {a = c; return 1;} > (In most concurrency books and papers instructions within angle brackets < > means that everything within the brackets is done in one uninterruptible, atomic action.) "
    Is this right?
    public synchronized int compareAndSwap(Object a, Object b, Object c)
            if ( a.equals( c ) )
                c = b;
                return 0;
            a = c;
            return 1;
        }Or is this?
    public int compareAndSwap(Object a, Object b, Object c)
            synchronized ( a )
                synchronized ( b )
                    synchronized ( c )
                        if ( a.equals( c ) )
                            c = b;
                            return 0;
                        a = c;
                        return 1;
        }Or am I totally off base? I think the latter is right as it prevents the objects themselves from being messed with.

    As far as making it an atomic action, you do that
    with synchronized, BUT more detail might be needed
    about the context in which it's supposed to be atomic
    to know what to sync on.OK, thanks. I was thinking I was crazy or something, but his question is just unclear. I have no idea what he wants and I'm not sure he does either.
    Thanks.

  • Question about SunStudio v12.3 and compiling on multicore multithreaded T5240

    Hi,
    I purchased the first multicore/multithreaded server for our company to replace SunFire V240 and v445.  The server I got is T5240 with 2x4 core 1.2GHz CPUS.
    I am running Sparc Solaris 10u11 on this server
    I installed SunStudio v12.3 and compiled mysql v5.5.19, which took an hour.  When I compiled on a SunFire v240 with 2 1.5G CPUs, the the compile took 1/2hour.  Now I know the single CPU on the 5240 is smaller than the v240 but I thought it would be faster on the 5240. I used the same compile script (see below).
    Is compiling a program just use a single CPU no matter what the capabilities?  Is there an option I can pass to have it use all the server resources so it can compile faster?   This is a web server and I want to make sure all the programs I compile can utilize all the capabilities of the cores and threads.
    If this is not the forum for this, any suggestions on where I can get help with this would be appreciated.
    Thank you.
    -----------------------------------  mysql compile script -------------------------------
    #!/bin/sh
    PATH=/opt/SUNWspro/bin:/usr/ccs/bin:/usr/sfw/bin:/usr/local/bin:.:/usr/bin:/usr/sbin:/usr/ucb:/etc:/usr/local/cmake/bin; export PATH
    CC=cc; export CC
    CXX=CC; export CXX
    /usr/local/cmake/bin/cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/home1/mysql_data -DSYSCONFDIR=/etc -DWITH_INNOBASE_STORAGE_ENGINE=1

    Each compilation is single-threaded. When you run a serial make, you get one compilation at a time.
    The way to improve throughput is to use a parallel make that can run more than one task simultaneously. I am not familiar with cmake. I took a quick look at the documentation at cmake.org, but could not tell whether cmake offers a parallel make option. Both GNU gmake and the dmake that comes with Studio do. (Studio dmake is the same as Solaris make, with extensions for parallel and distributed job management.) Assuming  there is enough memory, I use a rule of thumb of setting the max parallel jobs at 1 per core. You can find out the number of cores on Solaris this way:
         /usr/sbin/psrinfo | grep -c on-line
    Setting up the makefile for parallel make requires some attention to be sure you don't try to build parts out of sequence. Either all dependencies must be made explicit, or you need a way to say "wait for A to be done before starting B". (Both gmake and dmake have this feature.)  I don't know whether mysql makefiles are ready for parallel make, but you can probably find out at mysql.org, along with whether it works with dmake or gmake. (Each make variation has some usually minor incompatibilities with the others.)
    Message was edited by: Steve_Clamage

  • *Newbie Question* Acrobat 8.1 SDK: Converting Files and Multithreading

    I'm new to the SDK concept so please bare with me:
    1.) Can .DWG files be converted directly to PDFs?
    2.) **Must a version of Adobe Acrobat be installed on a computer for an application to function if it is using the SDKs class libraries?
    3.) If the application is installed on one computer, how many users are allowed to access it simultaneously.
    Thanks for the answers!

    >1.) Can .DWG files be converted directly to PDFs?
    Acrobat can use AutoCAD to do this, through the user interface. A
    plug-in can also invoke this.
    >2.) **Must a version of Adobe Acrobat be installed on a computer for an application to function if it is using the SDKs class libraries?
    Absolutely. Just as the Windows SDK is for computers with Windows on
    it, so the Acrobat SDK is for computers with Acrobat on it. The SDK
    itself does not add any interfaces, they all exist in Acrobat.
    >3.) If the application is installed on one computer, how many users are allowed to access it simultaneously.
    Only the logged in user. Acrobat is not for network or server use.
    Aandi Inston

  • Hi Chris -- follow up to my question about using TSQ to store strings of different sizes

    Thanks for your response.
    I did read about those method you mentioned. I have some troubles with each method:
    1/ Using TSQ as byte stream.
    This is what I chose to use. I basically write to the queue the way you described with an exception about the number of byte to write. I did as followed:
    CmtWriteTSQData (tsqHandle, buffer, strlen (buffer),TSQ_INFINITE_TIMEOUT, NULL);
    with buffer as the buffer containing my string. Note that strlen(buffer) is not same each time. Also a thread is doing the writing to the queue and another thread is doing the reading. This leads to my next question: How do you read these strings out?
    Right now I am reading one
    byte at a time with:
    while (1)
    CmtReadTSQData (tsqHandle, tempbuf, 1, 10, 0);
    in a loop, with tempbuf to contain this single char, and then store it in another buffer until I read out a CR of LF which signals the end of a string.
    Will I have any problem?
    Could you please provide an alternative?
    2/ Using TSQ to contain pointers to strings.
    I haven't tried this method since I think it requires allocation of rather large static array of buffer and also requires keeping track of these pointer in a link list.
    Would you elaborate how you would use TSQ this way in my case.
    3/ Lastly, the way I described in (1) works only if I have the main thread to do writing, and another thread to do reading. Some how it doesn't work when I used one thread to do writing, one thread to do reading, and the main thread to handle user interface. I found out that the program spends all its time in the reading thread (inside the while loop).
    Why is it different if the writ
    ing thread is the main thread? Do I miss something like priority,... or anything like that?
    Thank you so much.

    You really should consider using event driven reading. There is examples of this in the Multithreading examples in cvi\samples\utility\Threading. Then you will get an event in the reader thread whenever a certain number of items are available to read. If you use the byte stream method, you should send the message length with each method so you know how to package the messages back on the reader side.
    For the pointer method, you would malloc the buffer on the writer side, send the pointer to the reader, then the reader would free the memory when it is done with the data.
    I don't understand why what you are describing in 3 occurs. If you aren't setting priority to something other than default, then each thread should get time. If you want to free up time i
    n a thread that is taking to much, just put a small Delay in that thread.
    If you want more help on this, you can look at the examples I mentioned above, read the Multithreading Overview available in PDF form in the cvi\bin directory or contact NI support at http://www.ni.com/ask.
    Best Regards,
    Chris Matthews
    Measurement Studio Support Manager

  • Few questions - game loop, data types, speed

    Hello, I have a few questions after studying some topics in this forum regarding game creation:
    1) What's the fastest way to wait in the game loop? I've seen two approaches:
    thread.sleep(10)andsynchronized(this) { wait(10); }2) What data types shall I use? In C++ I use to prefer int over short in all cases, because 32bit hardware works faster with integers. Is this same on cell phones?
    3) Speed of applications is slow. I just wonder wheter it's my fault. I was testing application, which only cleared the buffer and outputted FPS and I got around 20 frames. It was Nokia 6300 with 240x320 display. After testing on other phones I've found out that the bigger the resolution, the slower the game is going. Is this normal?
    Thanks for replies...

    1) You're not going to notice any really speed difference between the two code snippets. Read up on 'Threads', and you'll see why one may be used in place of the other depending on the situation. In general there may be a slight performance loss, however unnoticable, when using the synchronized version, but when you are multithreading it is likely necessary.
    sleep(int) is impossible to interrupt, so it's generally a no-no in most situations. However we are talking about devices where every bit of performance helps, so as long as it works for ya, it's not a big deal.
    2) The performance difference is fairly negligable, if any. The biggest thing to consider is memory requirements, and shorts take 1/2 the data.
    Also, many phones don't support floating point data types, so you'll likely need to use ints/longs to calculate your values if you want to have any accuracy beyond whole numbers. Doing something like shifting bits or using 1000x values in your calculations can get around most of the problems when you can't use floats.
    3) The biggest performance killers are IO, memory allocation, screen drawing; pretty much in that order. So I imagine that you are re-creating a new String object every time you output your FPS value on screen right? Doing that every frame would destroy any hopes of getting high-performance.
    Just be careful, and never allocate objects when you can avoid it. anything where you concat String objects using + will cause your performance to die a horrible painful slow death. Remove anything that says 'new' from your main loop, and all String operations, and it'll likely speed things up a lot for ya.
    Does your main loop have something like this?
    g.drawString("FPS: " + currentFps, 0,0,Graphics.TOP | Graphics.LEFT);
    This is very bad because of the String operation. It'll create a new String every frame.
    If you have any more specicif questions, or you'd just like to pick the brain of a mobile game dev, stop by my messageboard:
    http://attackgames.proboards84.com
    Message was edited by:
    hooble

Maybe you are looking for

  • How to register iTunes Connect if i do not have a Tax account no

    Can anyone please advice , how to register iTunes Connect if i do not have a Tax account no? I am interested to register iTune Connect and sell ibook, but I am not US citizen and do not live in US. I do not have an US Tax account no. How can i procee

  • What is the best practice for genereating seq in parent

    I'm wondering what the best practice is for generating seq in parent. I have the following tables: invoice(id, date, ...) invoice_line(invoice_id, seq, quantity, price ...) There are shown in 1 uix displaying invoice in form layout and invoice lines

  • IOS 5 Airplay bug discovered

    I've been having a vexing problem whereby if I send sound via AirPlay to one of my Airport Expresses the "Ringer and Alert Volume" always resets to 4. This seems to be an issue with older generation Airport Expresses. I was not able to try it with a

  • How do I eliminate duplicates from my nano

    How do I eliminate duplicates from my nano?

  • Byte Order?

    Does byte order matter when saving a TIFF? Even if it doesn't, I can't figure out why it defaults to Macintosh on one CS3 installation and IBM PC on another CS3 installation. Thanks!