Multithreaded problem in read and write thread

This is a producer consumer problem in a multi-threaded environment.
Assume that i have multiple consumer (Multiple read threads) and a
single producer(write thread).
I have a common data structure (say an int variable), being read and written into.
The write to the data sturcture happens occasionally (say at every 2 secs) but read happens contineously.
Since the read operation is contineous and done by multiple threads, making the read method synchronized will add
overhead(i.e read operation by one thread should not block the other read threads). But when ever write happens by
the write thread, that time the read operations should not be allowed.
Any ideas how to achive this ??

If all you're doing is reading an int, then just use regular Java synchronization. You'll actually get a performance hit if you're doing simple read operations, as stated in the ReadWriteLock documentation:
Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application.

Similar Messages

  • Seperate read and write thread example

    hi.
    can anyone tell me a simplest way to implement thread to read and write from the socket seperately without blocing each other?
    how do i create seperate threads for a client to write and read from a serversocket?
    maskeeeee

    hi.
    can anyone tell me a simplest way to implement thread
    to read and write from the socket seperately without
    blocing each other?
    how do i create seperate threads for a client to write
    and read from a serversocket?Extend java.lang.Thread or implement java.lang.Runnable
    and RTFM for both of them. Lots of nice code examples in them thar
    API docs.
    matfud

  • Problem During reading and write local file

    Hi ,
    I had written a small applet program, it have function �readNwriteFile()� it read/write the local file
    This function works fine when I call it from start () function.
    But whenever I was trying to call this function from java script it gave me this exception.
    �java.security.AccessControlException: access denied (java.io.FilePermission C:\temp_jar\DSC01692.JPG read)�.
    Java script is working fine, I can access any another function from script The problem is some related to access
    I had set the permission in my policy file .this the permission that I had set.
    grant codebase "file:c:\temp_jar"{
    permission java.io.FilePermission "<< ALLFILES >> , "read ,write ,delete ,execute ";
    Java code.
    package com.ravindra;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    public class MialTest extends JApplet{
         public void init() {
         public void start(){
              readNwriteFile(); /// When I call this function from here It is working
         public byte [] readNwriteFile(){
              try {
                   File localfile = null;
                   localfile = new File("C:\\temp_jar\\DSC01692.JPG");
                   FileInputStream fs = new FileInputStream(localfile);
                   ByteArrayOutputStream bs = new ByteArrayOutputStream() ;
                   int actual_data = (int)fs.read();
                   while(actual_data > -1){
                        bs.write(actual_data);
                        actual_data = (int)fs.read();
                   byte [] final_data = bs.toByteArray();
                   File out_file = new File("C:\\temp_jar\\Ravindra_test.JPG");
                   FileOutputStream out_stream = new FileOutputStream(out_file);
                   out_stream.write(final_data);
                   out_stream.flush();
                   fs.close();
                   bs.close();
                   localfile = null;fs = null; bs = null;
                   return final_data;
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return null;
    Java Script Code:

    Hi ,
    I had written a small applet program, it have function �readNwriteFile()� it read/write the local file
    This function works fine when I call it from start () function.
    But whenever I was trying to call this function from java script it gave me this exception.
    �java.security.AccessControlException: access denied (java.io.FilePermission C:\temp_jar\DSC01692.JPG read)�.
    Java script is working fine, I can access any another function from script The problem is some related to access
    I had set the permission in my policy file .this the permission that I had set.
    grant codebase "file:c:\temp_jar"{
    permission java.io.FilePermission "<< ALLFILES >> , "read ,write ,delete ,execute ";
    Java code.
    package com.ravindra;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    public class MialTest extends JApplet{
         public void init() {
         public void start(){
              readNwriteFile(); /// When I call this function from here It is working
         public byte [] readNwriteFile(){
              try {
                   File localfile = null;
                   localfile = new File("C:\\temp_jar\\DSC01692.JPG");
                   FileInputStream fs = new FileInputStream(localfile);
                   ByteArrayOutputStream bs = new ByteArrayOutputStream() ;
                   int actual_data = (int)fs.read();
                   while(actual_data > -1){
                        bs.write(actual_data);
                        actual_data = (int)fs.read();
                   byte [] final_data = bs.toByteArray();
                   File out_file = new File("C:\\temp_jar\\Ravindra_test.JPG");
                   FileOutputStream out_stream = new FileOutputStream(out_file);
                   out_stream.write(final_data);
                   out_stream.flush();
                   fs.close();
                   bs.close();
                   localfile = null;fs = null; bs = null;
                   return final_data;
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return null;
    Java Script Code:

  • Problem to read and write files on hdd out of html with an Applet ????

    hi there,
    i wrote an applet for loading a file from HDD or saving data out of a cookie in a file on a hdd.
    when i compile the class there are warnings about "unchecked method invocation" and "unchecked conversion".
    what did i do wrong?
    i think it's about this function:
    AccessController.doPrivileged(new PrivilegedAction()
    public Object run()
    if(saveCartAtOnce.toLowerCase().compareTo("true")== 0)
    SaveShoppingCart();
    }//if
    return null;
    }// public Object run
    });//AccessController
    could anyone help me?
    i could also send the whole class then....
    thanks a lot.
    greetings
    Volker Becht
    [email protected]

    OK
    now i will post the whole class.
    my questen is: what have i to do so that anything runs?
    if anyone will need a file example which should be read
    into the calss i will email it.
    package de.CATALOGcreator.shoppingcart;
    import java.awt.*;
    import java.io.*;
    import java.applet.*;
    import java.util.*;
    import java.security.*;
    import netscape.javascript.*;
    public class shoppingcart extends java.applet.Applet
         private static final long serialVersionUID = 1234567890L;
       //Explanation of the possible Parameters of the applet, all of the following
        //parameters need not be given explicitely, because they have default values.
        String errorMessageInvalidFileFormat = "";  //set the ErrorMessage String for InvalidFileFormat when loading
        String openDialogTitle = "";                //set the Open Dialog Title
        String saveDialogTitle = "";                //set the Save Dialog Title
        String articleNumberString = "";            //set the ArticleNumber of the CSV headline
        String articleNameString = "";              //set the ArticleName of the CSV headline
        String amountString = "";                   //set the AmountName of the CSV headline
        String priceString = "";                    //set the PriceName of the CSV headline
        String delimiterString ="";                 //set the Delimiter for the Output-csv
        String inputdelimiterString ="";            //set the Delimiter for the Intput-csv
        //No parameter, this String is built from articleNumberString, articleNameString, amountString and
        //priceString and delimiterString in the following manner:
        //headline = articleNumberString + delimiterString + articleNameString + delimiterString + amountString+ delimiterString  + priceString;
        //see: init();
        String headline = "";                       //set the Headline of the csv-file
        //Another parameter is saveCartAtOnce, which says, if the save-Dialog is schown
        //at once when the applet is initialized. If the value is "true", the dialog shows
        //at once, in all other cases (also if parameter does not exist) you have to
        //call SaveShoppingCart explicitely.
        String saveCartAtOnce;
       public void init()
            try
                   //set the default setting for the Paramters
                   openDialogTitle = this.getParam("openDialogTitle", "Open Shopping Cart");
                   saveDialogTitle = this.getParam("saveDialogTitle", "Save File As");
                   errorMessageInvalidFileFormat = this.getParam("errorMessageInvalidFileFormat", "Invalid File Format!\nLoading stopped.");
                   delimiterString = this.getParam("delimiterString", "||");
                   inputdelimiterString= this.getParam("inputdelimiterString", ",");
                   articleNumberString = this.getParam("articleNumberString", "Article Number");
                   articleNameString = this.getParam("articleNameString", "Article");
                   amountString = this.getParam("amountString", "Amount");
                   priceString = this.getParam("priceString", "Price");
                   headline = articleNumberString + delimiterString + articleNameString + delimiterString + amountString + delimiterString  + priceString;
                   saveCartAtOnce = this.getParameter("saveCartAtOnce");
                   AccessController.doPrivileged(new PrivilegedAction()
                                  public Object run()
                                       if(saveCartAtOnce.toLowerCase().compareTo("true")== 0)
                                            SaveShoppingCart();
                                            //LoadShoppingCart();
                                       }//if
                                       return null;
                                  }// public Object run
                   });//AccessController
              catch(Exception e)
                   e.printStackTrace();
        }//void init
        public void  SaveShoppingCart()
            DataOutputStream dos;
            String myFile;
            File f ;
             myFile =  SaveDialog();
               if(myFile!=null)
                    f = new File(myFile);
                   String Artikel=getParameter("Artikel");
                   String Anzahl=getParameter("MyAnzahl");
                   String Bezeichnung=getParameter("Bezeichnung");
                   String Preis=getParameter("Preis");
                   StringTokenizer stArticle = new StringTokenizer(Artikel, inputdelimiterString);
                   StringTokenizer stAnzahl = new StringTokenizer(Anzahl, inputdelimiterString);
                   StringTokenizer stBezeichnung = new StringTokenizer(Bezeichnung, inputdelimiterString);
                   StringTokenizer stPreis = new StringTokenizer(Preis, inputdelimiterString);
                   JSObject.getWindow(this).eval("alert('"+ Artikel +"')");
                     try
                          dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myFile),128));
                          // Line 1
                        dos.writeChars(headline + "\n");
                          while (stArticle.hasMoreTokens())
                              String tmpArticle=stArticle.nextToken();
                              String tmpAnzahl=stAnzahl.nextToken();
                              String tmpBezeichnung=stBezeichnung.nextToken();
                              String tmpPreis=stPreis.nextToken();
                              dos.writeChars(tmpArticle + delimiterString + tmpBezeichnung + delimiterString +tmpPreis +  delimiterString + tmpAnzahl + "\n");
                        }//while
                          dos.flush();
                          System.out.println("Successfully wrote to the file named " + myFile + " -- go take a look at it!");
                          dos.close();
                   }//try
                      catch (SecurityException e)
                        System.out.println("JavaSoft SaveShoppingCart: SecurityException\nMessage:" + e.getMessage() + "\nStackTrace:");
                        e.printStackTrace(System.out);
                   }//catch
                   catch (IOException ioe)
                        System.out.println("JavaSoft SaveShoppingCart: IOexception\nMessage:" + ioe.getMessage() + "\nStackTrace:");
                        ioe.printStackTrace(System.out);
                   }//catch
              }//if
        }//void  SaveShoppingCart
        private String SaveDialog()
            try
               //Date now = new Date(System.currentTimeMillis());
                Calendar rightNow = Calendar.getInstance();
               //SystemDate
                //String strDay = Integer.toString(now.getDate());
                String strDay = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH));
                //String strMonth = Integer.toString(now.getMonth()+1);
                String strMonth = Integer.toString(rightNow.get(Calendar.MONTH));
                //String strYear = Integer.toString(now.getYear()+1900);
                String strYear = Integer.toString(rightNow.get(Calendar.YEAR));
                //SystemTime
                //String strHoure = Integer.toString(now.getHours());
                String strHoure = Integer.toString(rightNow.get(Calendar.HOUR));
                //String strMinutes = Integer.toString(now.getMinutes());
                String strMinutes = Integer.toString(rightNow.get(Calendar.MINUTE));
                //String strSeconds = Integer.toString(now.getSeconds());
                String strSeconds = Integer.toString(rightNow.get(Calendar.SECOND));
                //set SystemDate+SystemTime
                String strDate=strDay+"_"+strMonth+"_"+strYear+"_"+strHoure+"_"+strMinutes+"_"+strSeconds;
                //set SaveName as *.csv
                String SaveAs = strDate + ".csv";
                FileDialog fd = new FileDialog (new Frame(), "Save File As", FileDialog.SAVE);
                fd.setFile(SaveAs);
                fd.setVisible(true);
                //Value Save or Cancel Button
                if((fd.getDirectory() == null) || (fd.getFile() == null)) // user pressed the cancel - button
                    return null;
                }//if
                else // user pressed save - button
                    return fd.getDirectory() + fd.getFile();
                }//else
            }//try
            catch (SecurityException e)
                   System.out.println("JavaSoft String SaveDialog: SecurityException\nMessage:" + e.getMessage() + "\nStackTrace:");
                   e.printStackTrace(System.out);
                  return null;
            }//catch
        }// String SaveDialog
        public String OpenDialog()
               FileDialog fd = new FileDialog (new Frame(), openDialogTitle, FileDialog.LOAD);
               fd.setVisible(true);
               return fd.getDirectory() + fd.getFile();
        }//String OpenDialog
        private String getParam( String paramName, String defaultValue )
              String value = getParameter( paramName );
              if ( value != null )
                   return value;
              }//if
              return defaultValue;
        }//String getParam
        public void LoadShoppingCart()
            String myFile;
            File f ;
            myFile =  OpenDialog();
            if(myFile!=null)
                   f = new File(myFile);
                   String rl = "";
                   Object[] Obj = new Object[2];
                   try
                        DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(myFile),128));
                        // Line 1
                        String FirstLine = myReadLine(dis);
                        JSObject.getWindow(this).eval("alert('"+ FirstLine +"')");
                        if(FirstLine.startsWith(headline))
                             while ( (rl = myReadLine(dis)) != null)
                                  //examines correct delimiter
                                  StringTokenizer token = new StringTokenizer (rl, delimiterString);
                                  if(token.countTokens()!= 4)
                                       dis.close();
                                       JSObject.getWindow(this).eval("alert('"+ errorMessageInvalidFileFormat +"')");
                                  }//if
                                Obj[0]= (Object)rl;
                                Obj[1]= (Object)delimiterString;
                                JSObject.getWindow(this).call("addCSVArticle",Obj); // this=applet
                             }//while
                             JSObject.getWindow(this).call("importFinished",null);
                        else
                             dis.close();
                             JSObject.getWindow(this).eval("alert('"+ errorMessageInvalidFileFormat +"')");
                             //System.exit(-1);
                        }//else
                        dis.close();
                   }//try
                      catch (SecurityException e)
                        System.out.println("JavaSoft LoadShoppingCart: SecurityException\nMessage:" + e.getMessage() + "\nStackTrace:");
                        e.printStackTrace(System.out);
                   }//catch
                   catch (IOException ioe)
                        System.out.println("JavaSoft LoadShoppingCart: IOexception\nMessage:" + ioe.getMessage() + "\nStackTrace:");
                        ioe.printStackTrace(System.out);
                   }//catch
                   catch(Exception exc)
                        System.out.println("JavaSoft LoadShoppingCart: Exception\nMessage:" + exc.getMessage() + "\nStackTrace:");
                        exc.printStackTrace(System.out);
                   }//catch
              }//if
        }//void LoadShoppingCart
        private String myReadLine(DataInputStream dis)
            char tmp;
            String line = "";
            try
                while((tmp = dis.readChar())!= '\n')
                    line += tmp;
                return line;
            }//try
            catch(IOException ioexc)
                return null;
            }//catch
        }//String myReadLine
        public boolean isInitialized()
              return true;
    }//public class ShoppingCart extends java.applet.Applet[/i]

  • Windows 2008 R2 Folder assign permission "Read and Write" problem with *.doc file

    Hello All,
    I am a new one here,
    I am sorry for any mistakes and also my english is so poor.
    M Brother company runing Windows 2008 R2 as Active Directory...
    We have folder Name: Admin
    and in this folder, there are alot documents files as : *.doc, *.dwg, *.txt etc.....
    All user accesing to these files and they can open to edit and save...
    One day my brother want me to set Admin folder for all users just"Read and Write.." mean they still can open files to edit and save... but can't delete..
    I did success with this..
    But only one thing happen.. when they open *.doc file to edit and attempting to save, the message alert" access denide " and they can only "SAVE AS"...We don't want "Save as"
    Could you show me how can we fix error with *.doc file while they trying to save? because it allow only save as.. but other files as *.text file or *.dwg they can save without problem..
    Could expert here ever face this issues and fix by yourself, please share me with this..
    Please help me..
    Best regards,

    Hi,
    Office programs are specific. They will create a temp file when edit, then the temp file will be deleted when close. So Delete permission is needed for users to saving Office files like Excel/Word.
    For more detaile information, please refer to the thread below:
    Special Permissions - User cannot save files
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/721fb2f1-205b-46e5-a3dc-3029e5df9b5b/special-permissions-user-cannot-save-files
    Best Regards,
    Mandy 
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • Can't stop synchronized threads with I/O read and write

    I have two synchronized threads which doing read and write from and into a file.
    One thread called "reader" which does reading, encoding, etc from a source file and puts its output in a pre-defined variable. Another called "writer" which puts the reader's output into a file ( not the source file ). Both thread will notify each other when they've finished each of their part. It's similiar to CubyHole example of Java Tutorial example from Sun.
    But somehow it seems like the threads keep spawning and won't die. Even if the source file has been all read and the data has been fully written, calling interrupt(), return, etc has no effect. The threads will keep running untill System.exit() called.
    Is it because the threads were blocked for I/O operation and the only way to kill them is to close the I/O ?
    To be honest, it's not only stop the threads that I want to, I also want to somehow pause the threads manually in the middle of the process.
    Is it possible ?
    Cheers.!!!

    The example code for the problem using 4 classes called :
    - libReadWrite ( class holding methods for aplication operations )
    - reader ( thread class responsible for reading data )
    - writer ( thread class responsible for writing data )
    - myGUI ( user interface class )
    All of them written in different file.
    // libReadWrite
    pubic class libReadWrite {
    private boolean dataReady;
    private String theData;
    //read data
    public synchronized void read(String inputFile) {
    while (dataReady == true) {
    try {
    wait();
    } catch (InterruptedException ex) {}
    RandomAccessFile raf = new RandomAccessFile(inputFile, "r"); // I'm using raf here because there are a lot of seek operations
    theData = "whatever"; // final data after several unlist processes
    dataReady = true;
    notifyAll();
    public synchronized void write(String outputFile) {
    while (dataReady == false) {
    try {
    wait();
    } catch (InterruptedException ex) {}
    DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFile, true));
    output.writeBytes(theData);
    dataReady = false;
    notifyAll();
    //Reader
    public class reader extends Thread {
    private libReadWrite myLib;
    private String inputFile;
    public reader (libReadWrite myLib, String inputFile) {
    this.myLib = myLib;
    this.inputFile = inputFile;
    public void run() {
    while (!isInterrupted()) {
    myLib.read(inputFile); <-- this code running within a loop
    return;
    public class writer extends Thread {
    private libReadWrite myLib;
    private String outputFile;
    public writer (libReadWrite myLib, String outputFile) {
    this.myLib = myLib;
    this.outputFile = outputFile;
    public void run() {
    while (!isInterrupted()) {
    myLib.write(outputFile); <-- this code running within a loop
    try {
    sleep(int)(Math.random() + 100);
    } catch (InterruptedException ex) {}
    return;
    //myGUI
    public class myGUI extends JFrame {
    private libReadWrite lib;
    private reader readerRunner;
    private writer writerRunner;
    //Those private variables initialized when the JFrame open (windowOpened)
    libReadWrite lib = new libReadWrite();
    reader readerRunner = new reader("inputfile.txt");
    writer writerRunner = new writer("outputfile.txt");
    //A lot of gui stuffs here but the thing is below. The code is executed from a button actionPerformed
    if (button.getText().equals("Run me")) {
    readerRunner.start();
    writerRunner.start();
    button.setText("Stop me");
    } else {
    readerRunner.interrupt();
    writerRunner.interrupt();
    }

  • Problem with air read and write smb shared directory of file

    hi, everyone.
    I'm want to access smb directory of file,And to read and
    write operation, I would like to ask how I should do?
    Thanks!

    You can't access any OS facility nor execute arbitrary command.
    So the best solution is to mount samba directory BEFORE run your AIR application; you eventually can create a script that mount samba (and asks password) and then run you AIR application.
    see
    http://www.mikechambers.com/blog/2008/01/17/commandproxy-net-air-integration-proof-of-conc ept/
    for a more complex solution.

  • How do I read and write to text files on a remote computer's hard drive

    I would like to read and write data to a text file on a remote computer. This is easily accomplished using one of the file functions such as "write characters to file.vi". If I am already connected to the remote computer, all I need to do is specify the path to the particular file and it will work fine.
    My problem is that I want to connect to the remote computer programatically within LabVIEW (I do not want to have to use the computer's OS to establish the connection. Is there a function that I can use to do this?
    Thomas D. Schaefer
    Wells Manufacturing Corp

    Yariv,
    You should really start a new thread with a new question like this, so that more people see it. Some people look primarily at threads that have no responses yet. Also, don't post the exact same question in multiple places. Or, if you must cross-post to some other forum, make sure to mention it in your question text.
    I'm happy to be a brick in your Western Wall, but I'm not sure what the main objective is here. Is the main problem really getting access to the "X bytes received in Y seconds at Z bytes/sec" string? Or is it accomplishing the file transfer? And what OS and LabVIEW version are you running?
    I think your problem is that you the LabVIEW System Exec command does not allow for the degree of interactivity that you need if you want to issue a sequence of commands to a command-line executable. However, under Windows XP (and, presumably, other Windows versions, though I can't check), you can tell the FTP executable to use commands from a textfile script by using the -s switch, and you can override the prompts during multiple file transfers with the -i switch:
    ftp -i -s:FILEPATH SERVERNAME
    If you issue a command in this format to System Exec, and make sure to create a file at FILEPATH with your command sequence (one per line), then you should at least accomplish the FTP actions. This won't give you the transfer details in the standard output, unfortunately. However, if you just want a general sense of how much was transferred and how quickly it happened, you can code that in LabVIEW by getting the resulting file sizes and using Tick Count before and after the System Exec call to see how long the transfer took.
    Hope that helps,
    John

  • Why does this class not read and write at same time???

    I had another thread where i was trying to combine two class files together
    http://forum.java.sun.com/thread.jspa?threadID=5146796
    I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class testing extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
       //private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
       private Employee record;
    //////////////////////////////////////from read
    private ObjectInputStream input;
       private JButton nextButton, openButton, nextRecordButton ;
       private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
    /////////////////////////////////////////////from read end
       // set up GUI
       public testing()
          super( "Employee Data" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // nine textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          SaveAs = userInterface.getSaveAsButton();
          SaveAs.setText( "Save as.." );
    //////////////////from read
    openButton = userInterface.getOpenFileButton();
          openButton.setText( "Open File" );
    openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    ///////////from read end
          // register listener to call openFile when button pressed
          SaveAs.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   SaveLocation();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          SaveToFile = userInterface.getSaveStoreToFileButton();
          SaveToFile.setText( "Save to store and to file need to split this task up" );
          SaveToFile.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          SaveToFile.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
             } // end anonymous inner class
          ); // end call to addActionListener
    Exit = userInterface.getExitAndSaveButton();
          Exit.setText( "Exit " );
          Exit.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          Exit.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // adds record to to file
                   closeFile(); // closes everything
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
    ////////////////from read
      // enable user to select file to open
       private void openFile()
          // display file dialog so user can select file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                input = new ObjectInputStream(
                   new FileInputStream( fileName ) );
                openButton.setEnabled( false );
                nextButton.setEnabled( true );
             // process exceptions opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
    public void readRecord() // need to merger with next record
          Employee record;
          // input the values from the file
          try {
         record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);/////////ADDS record to Store
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
    // i added all those bits above split onto one line to look neater
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
       private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record content
    ///////////////////////////////////from read end
    private void SaveLocation()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                SaveAs.setEnabled( false );
                SaveToFile.setEnabled( true );
              Exit.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
    private void closeFile()
          // close file
          try {
              //you want to cycle through each recordand add them to store here.
                                            int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
    input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0)); // check if m or f prob check in employee
    if ( employeeNumber >= 0 ) {
                  /* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                                  //output.writeObject( record );
                   output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new testing();
    } // end class CreateSequentialFile

    Sure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
    I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
    So now we have a Big Ball Of Tar&trade; and I feel partly responsible.

  • Best Practice to Atomic Read and Write a Field In Database

    I am from Java Desktop Application background. May I know what is the best practice in J2EE, to atomic read and write a field in database. Currently, here is what I did
    // In Servlet.
    synchronized(private_static_final_object)
        int counter = read_counter_from_database();
        counter++;
        write_counter_back_to_database(counter);
    }However, I suspect the above method will work all the time.
    As my observation is that, if I have several web request at the same time, I am executing code within single instance of servlet, using different thread. The above method shall work, as different thread web request, are all referring to same "private_static_final_object"
    However, my guess is "single instance of servlet" is not guarantee. As after some time span, the previous instance of servlet may destroy, with another new instance of servlet being created.
    I also came across [http://code.google.com/appengine/docs/java/datastore/transactions.html|http://code.google.com/appengine/docs/java/datastore/transactions.html] in JDO. I am not sure whether they are going to solve the problem.
    // In Servlet.
    Transaction tx = pm.currentTransaction();
    tx.begin();
        int counter = read_counter_from_database();  // Line 1
        counter++;                                                  // Line 2
        write_counter_back_to_database(counter);    // Line 3
    tx.commit();Is the code guarantee only when Thread A finish execute Line 1 till Line 3 atomically, only Thread B can continue to execute Line 1 till Line 3 atomically?
    As I do not wish the following situation happen.
    (1) Thread A read counter from Database as 0
    (2) Thread A increment counter to 1
    (3) Thread B read counter from Database as 0
    (4) Thread A write counter as 1 to database
    (5) Thread B increment counter to 1
    (6) Thread B write counter as 1 to database
    What I wish is
    (1) Thread A read counter from Database as 0
    (2) Thread A increment counter to 1
    (4) Thread A write counter as 1 to database
    (3) Thread B read counter from Database as 1
    (5) Thread B increment counter to 2
    (6) Thread B write counter as 2 to database
    Thanks you.
    Edited by: yccheok on Oct 27, 2009 8:39 PM

    This is my understanding of the issue (you should research it further on you own to get a better understanding):
    I suggest you use local variables (ie, defined within a function), and keep away from static variables. Those local variables are thread safe. If you call functions within functions, its still thread safe. If you read or write to one record in a database using sql, its thread safe (you dont need a transaction). If you read/write to multiple tables and/or records, you probably need a transaction. Servlets are thread safe. You usually dont need the 'synchronized' word anywhere unless you have a function updating/reading a static variable and therefore want to ensure only one user is accessing the static varible at a time. Also do so if you are writing to some resource (such as a file, a variable in applicaton scope, session scope, or resource that everyone uses such as email server). You dont want more than one person at a time to write to it). Note the database is one of of those resources that is handled by transactions rather than the the synchronized keyword (the synchronized keyword is applied to your application only (not other applications that someone is running), whereas the transaction ensures all applications are locked out while you update those records in the database).
    By the way, if you have a static variable, you should have one and only one function (synchronized) that updates it that everyone uses. If you have more than one synchronized function, that updates it, its probably not thread safe.
    An example of a static variable you would use is a Datasource object (to obtain your database connections). You only need one connection pool in your application and you access it via the datasource variable.
    If you're unsure your code is thread safe, you can create two seperate threads that call the same block of functions repeatedly to ensure it works as expected.

  • File Read and Write using File Adapter in Bpel

    In Bpel Process i am using File Adapter ( Schema is Opaque) for read and write the file contents. i am able do successful deployment and read, write function in first time deployment, after that again i tired to run the application, its not going to write the content of file, its only writing the file with out data's or content in that file.
    Please help me...
    Saravanan

    Hi Eric
    In my domain.log file having the following details. In this file im unable to find out what the exact problem. Please look at this and help me.
    <2008-01-22 18:25:42,024> <INFO> <default.collaxa.cube.compiler> validating "C:\product\10.1.3.1\OracleAS_1\bpel\domains\default\tmp\.bpel_BPELProcess2_1.1_298e83988d77b6640c33dfeec11ed31b.tmp\BPELProcess2.bpel" ...
    <2008-01-22 18:25:49,850> <INFO> <default.collaxa.cube.engine.deployment> <CubeProcessFactory::generateProcessClass>
    Process "BPELProcess2" (revision "1.1") successfully compiled.
    <2008-01-22 18:25:49,914> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Loading JCAActivationAgent for {portType=Read_ptt}
    <2008-01-22 18:25:49,914> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::load - Locating Adapter Framework instance: OraBPEL
    <2008-01-22 18:25:49,930> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::load - Done loading JCAActivationAgent for processId='bpel://localhost/default/BPELProcess2~1.1/
    <2008-01-22 18:25:49,930> <INFO> <default.collaxa.cube.engine.deployment> Process "BPELProcess2" (revision "1.1") successfully loaded.
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::uninit Shutting down the JCA activation agent, processId='bpel://localhost/default/BPELProcess2~1.0/', activation properties={portType=Read_ptt}
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - performing endpointDeactivation for portType=Read_ptt, operation=Read
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Endpoint De-activation called in adapter for endpoint : D:\MAXIMUS_Project_Softwares\jdevstudiobase10132\jdev\mywork\MyLabs\BPELProcess2\in
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::init - Initializing the JCA activation agent, processId='bpel://localhost/default/BPELProcess2~1.1/
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::initiateInboundJcaEndpoint - Creating and initializing inbound JCA endpoint for:
    process='bpel://localhost/default/BPELProcess2~1.1/'
    domain='default'
    WSDL location='rd.wsdl'
    portType='Read_ptt'
    operation='Read'
    activation properties={portType=Read_ptt}
    <2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - endpointActivation for portType=Read_ptt, operation=Read
    <2008-01-22 18:26:02,730> <INFO> <default.collaxa.cube.activation> <File Adapter::Inbound> Endpoint Activation called in File Adapter for endpoint: D:\MAXIMUS_Project_Softwares\jdevstudiobase10132\jdev\mywork\MyLabs\BPELProcess2\in
    <2008-01-22 18:26:02,730> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - successfully completed endpointActivation for portType=Read_ptt, operation=Read
    <2008-01-22 18:26:02,890> <WARN> <default.collaxa.cube.activation> <File Adapter::Inbound> PollWork::run exiting, Worker thread will die
    <2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Managed Connection Created
    <2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Connection Created
    <2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> FileInteraction Created

  • Why are my Datasocket OPC reads and writes so slow?

    I am creating an application (in LabView 6.1) that has to interface with 15-30 OPC tags (about half and half read and write) on a KepWare OPC server. It seems like the DSC Module would be overkill, but the datasocket write VIs seem to slow the system to a halt at about 6 tags. I saw something about using the legacy datasocket connect VIs, but would I really see a large performance boost from switching?
    In the existing code we have, I have seen that even the legacy VIs (our old code uses the older VIs) sometimes grind the system to a halt or lock it up completely if it loses sight of the OPC server. Has anyone else had problems with this?

    Hi IYUS,
    What OPC Server are you using?  What methods are you using to communicate?  If you are using IAOPC, have you installed the latest patch?
    Also, this post is nearly 2 years old.  You will probably get more visibility (and more help) if you post your questions in a new thread.
    Cheers,
    Spex
    National Instruments
    To the pessimist, the glass is half empty; to the optimist, the glass is half full; to the engineer, the glass is twice as big as it needs to be...

  • Help ,ImageIO exception to read and write

    Hi,
    I'm dynamically creating image files through screens utility of java(prog name:- Test_ScreenShot.java) and saving
    them in memory sequentially(pic0.jpg,pic1.jpg....etc).Simultaneously I'm accessing the saved files from another
    independent application(Prog name:- Test_Main.java) through piping(executing the application like this "Java
    Test_Screens|Java Test_Main").The application is in infinite loop.I'm using Version JDK 1.5
    I use java Image to read and write image:-
    My application was running well for days.But now I'm getting sudden exceptions.
    I got an exception while trying to save an dynamically generated image file in the local memory using the Image
    class.In brief I'm getting exactly 3 types of exceptions:-
    1)java.io.FileNotFoundException: pic5.jpg (Access is denied)
    2)"Exception in thread "main" java.lang.NullPointerException
    3)Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
    Here is the code snippent I wrote:
    /* Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect);
    // save captured image to jpg file
    ImageIO.write(image, "jpg", new File(outFileName));*/
    And here is the exception I am finding (I never found this before, I executed the code many times )
    =====================================================================================================================
    1)Exception Type 1:-
    java.io.FileNotFoundException: pic5.jpg (Access is denied)
    at java.io.RandomAccessFile.open(Native Method)
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
    at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:44)
    at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:37)
    at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:391)
    at javax.imageio.ImageIO.write(ImageIO.java:1483)
    at Test_ScreenShot.main(Test_ScreenShot.java:112)
    at Test_Main.main(Test_Main.java:466)
    at Test_ScreenShot.main(Test_ScreenShot.java:129)
    2)Exception Type 2:-
    "Exception in thread "main" java.lang.NullPointerException
    at Picture.width(Picture.java:84)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:38)
    at Test_Main.main(Test_Main.java:88)"
    ============================================================================================
    Now I tried the following as alternative of ImageIO(from jdk 1.2)
    to read image:-
    FileInputStream fis = new FileInputStream(file);
    JPEGImageDecoder jpeg = JPEGCodec.createJPEGDecoder(fis);
    jpeg.decodeAsBufferedImage();
    fis.close();
    But after running a long time suddenly its giving following exceptions:-
    ==============================================================================================
    Exception Type 3:- )
    Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
    at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)
    at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source)
    Exception Type 4:- )
    javax.imageio.IIOException: Not a JPEG file: starts with 0xff 0xd9
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Source)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source)
    at javax.imageio.ImageIO.read(Unknown Source)
    at javax.imageio.ImageIO.read(Unknown Source)
    at Picture.<init>(Picture.java:22)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
    at Test_Main.main(Test_Main.java:88)
    Exception in thread "main" java.lang.RuntimeException: Could not open file: pic45.jpg
    at Picture.<init>(Picture.java:27)
    at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
    at Test_Main.main(Test_Main.java:88)
    My question is:-
    1)Where is the actual problem?Is it any kind of bug?
    2)I'm using the concept of piping recently to execute the application.Can it be the cause?
         When I googled I found the following informations.There is a bug in ImageIO while trying to write image file.But
    I'm not sure about that it will be relevent here :-
    1)from sun's bug database:-
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6247985
    2)from SUN Developer Forums
    http://forum.java.sun.com/thread.jspa?threadID=768917&messageID=4382833
    3)from Java.NET forum(here they r getting the bug while they r using createScreenCapture() method of robot class,I am
    also using that in my code)
    http://forums.java.net/jive/thread.jspa?messageID=123247
    4)from SUN's archieve
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0207&L=java-imageio-interest&D=0&P=1483
    5)Here is the actual implemetation of ImageIO class.I'm getting error at 391 no. line.
    http://kickjava.com/src/javax/imageio/ImageIO.java.htm
    Thanks And Regards
    Subhadip

    Hello,
    I am writng to ask a doubt I have been encountered. I have an array of Image URL's and I am downloading the images using thses URL for each index. The example for an image URL will be as follows:
    http://www.firstmonday.org/issues/issue6_10/wiggins/google-3oct2001.gifIf the URL is abroken link, I am getting the exception. But if the URL is somewhat hanging (which means when u open that URL in IE or Mozilla, the statuc bar for downloading the image will be hanging).
    So i want to set a timer for every link while downloading. may be 10min. My idea is if in that 10min, if code does not completes downloading the images, then ignore that link and proceed furthur.
    Can u please tell me how to write this.. Please tell me any other idea to tackle this problem.
    Thank you,
    Chaitanya

  • Mac desktop. 10.6.8. Text edit. Not locked. Read and write. Still, documents are locking when they are moved from desktop to another folder on the server. Techies can't figure it out here. What am I not doing?

    Mac desktop. 10.6.8. Text edit. Not locked. Read and write, not read only. Documents are locking when they are moved from desktop to another folder or saved directly into that folder on the server. Not happening with anyone else but me and the boss's computer so has to be in the properties for my text edit software. Techies can't figure it out after trying for two weeks. Boss can do a cut and paste and put into a new document, but that's starting to become a problem.

    Mac desktop. 10.6.8. Text edit. Not locked. Read and write, not read only. Documents are locking when they are moved from desktop to another folder or saved directly into that folder on the server. Not happening with anyone else but me and the boss's computer so has to be in the properties for my text edit software. Techies can't figure it out after trying for two weeks. Boss can do a cut and paste and put into a new document, but that's starting to become a problem.

  • Need help to read and write using UTF-16LE

    Hello,
    I am in need of yr help.
    In my application i am using UTF-16LE to export and import the data when i am doing immediate.
    And sometimes i need to do the import in an scheduled formate..i.e the export and imort will happend in the specified time.
    But in my application when i am doing scheduled import, they used the URL class to build the URL for that file and copy the data to one temp file to do the event later.
    The importing file is in UTF-16LE formate and i need to write the code for that encoding formate.
    The problem is when i am doing scheduled import i need to copy the data of the file into one temp place and they doing the import.
    When copying the data from one file to the temp i cant use the UTF-16LE encoding into the URL .And if i get the path from the URl and creating the reader and writer its giving the FileNotFound exception.
    Here is the excisting code,
    protected void copyFile(String rootURL, String fileName) {
    URL url = null;
    try {
    url = new URL(rootURL);
    } catch(java.net.MalformedURLException ex) {
    if(url != null) {
    BufferedWriter out = null;
    BufferedReader in = null;
    try {
    out = new BufferedWriter(new FileWriter(fileName));
    in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    do {
    line = in.readLine();
    if(line != null) {
    out.write(line, 0, line.length());
    out.newLine();
    } while(line != null);
    in.close();
    out.close();
    } catch(Exception ex) {
    Here String rootURL is the real file name from where i have to get the data and its UTF-16LE formate.And String fileName is the tem filename and it logical one.
    I think i tried to describe the problem.
    Plz anyone help me.
    Thanks in advance.

    Hello,
    thanks for yr reply...
    I did the as per yr words using StreamWriter but the problem is i need a temp file name to create writer to write into that.
    but its an logical one and its not in real so if i create Streamwriten in that its through FileNotFound exception.
    The only problem is the existing code build using URL and i can change all the lines and its very difficult because its vast amount of data.
    Is anyother way to solve this issue?
    Once again thanks..

Maybe you are looking for

  • Question about error message in Adobe Reader

    I reinstalled Reader and now when I try to open a program I get the error message Acrobat Failed to load its Core DLL

  • "Characteristic is blocked by conversion" -- "No Nametab Exist"

    Hi all, I have a serious problem. I have an infoobject with master data time dependent. I have switched one field from "Time-Dependent" to "not Time Dependent". In development environment no problem arises. When transporting in quality environment, t

  • How to change sy=uname value in selection screen?

    Hi, In selection screen i declared a default file path like this.. C:\Documents and Settings\User Name\Vendor\'. when it displays the path in selection screen, I want to replace that user name with SY-UNAME FIELD. Can any one let me know where i can

  • Can you create HTML5 with Dreamweaver CS4?

    Hello. Can you create HTML5 with Dreamweaver CS4? Are there workarounds if not? I am using a PC on Windows 7. Thank you.

  • Column & Row Headings

    Is there any way in Numbers to suppress the display (viewing and/or printing) of row and/or column headings? For example, I don't want to see A,B,C,... across the top or 1.2.3... down the left side. Besides, by suppressing these displays I should be