Multiple applets, single JVM == out of memory

Consider the following applet (MS IE 6, JRE 1.4.2_04)
public class DgAppletTest extends JApplet
double nums[];
public void init() {
nums = new double[10000000];
public void start() {
public void stop() {
public void destroy() {
This does nothing except allocate a large array. When this is delivered to the browser as part of an html page, a JVM instance is created and so on. The plug in control panel confirms the memory usage. When the user closes the browser window, the applet is "destroyed" but curiously the memory is not gc'ed. The next time the page is delivered the same JVM is used with the current memory situation. The result is that very soon the memory is exhausted.
Once upon a time, Microsoft launched each browser instance into a separate process. No longer, although there is a registry hack to make it do so. When as a separate process, each browser window instantiates a new JVM. In this scenario, there's no problem. However, hacking the registry is not a solution, nor is telling the end user to modify JVM startup parameters.
So, what am I not doing? (calling the gc within the applet has no effect on this). What's the trick to get the JVM to actually destroy the destroyed applet?
Thanks

http://forum.java.sun.com/thread.jspa?threadID=605153&messageID=3276004
Quote from another thread:
Objects are never null. Only references can be null. If you set the only reachable
reference to the object to null (or to any value other than pointing at that object), then the
object becomes eligible to be garbage collected. When--or if--it actually gets cleaned up
is beyond your control, but it's guaranteed to happen if the memory is needed.
Which is basacally the same as what this tells you:
http://java.sun.com/developer/technicalArticles/ALT/RefObj/
under
Softly Reachable

Similar Messages

  • Help please jvm out of memory

    Could some some please help me with this i hava a programe which is reading email from amd email sever using javamail.
    My problem is that when this pgrograme have to read more than 27 thousand emails and filter them at the same time but as soon as i get to 5900 the jvm runs out of memory. i have tried increaing memory using -Xms and Xms this seem to work but i still get memory leaking could some one have a look at my code i would be very happy to any light at to why or where the leak is comming from.
    at the moment i have managed to track the leak to the "searchEMail" method
    if you cam help my email is [email protected] or [email protected]
    =====================================================================
    EmailFilter.java
    wokoli
    =====================================================================
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.swing.JProgressBar;
    import javax.swing.JWindow;
    public class EmailFilter
      extends Authenticator implements EmailHelper
      protected String from=null;
      protected Session session=null;
      protected PasswordAuthentication authentication=null;
      private Properties props=null;
      private TreeMap bounced=null; 
      private long start=0;
      private long end=0;
      private PrintWriter out=null;
      private int blockSize=100;
      private Store store=null;
       public EmailFilter(Properties props){  
        this(null, null,props);
      public EmailFilter(String user, String host,Properties props)
      try{      
        if(props==null)
          props = new Properties();
          System.out.println("Reading properties file...");
          props.load(new FileInputStream("config.properties"));
          from = user + '@' + host;     
          props.setProperty("mail.user", user);
          props.setProperty("mail.host", host);
          props.setProperty("mail.password",user);     
      }catch(Exception e){
         e.printStackTrace();
        authentication = new PasswordAuthentication(props.getProperty("mail.user"),props.getProperty("mail.password"));
        props.setProperty("mail.store.protocol", "pop3");
        props.setProperty("mail.transport.protocol", "smtp");
        session = Session.getInstance(props, this);
        blockSize=Integer.parseInt(props.getProperty(BLOCKSIZE));
        this.props=props;       
        processCsvFile();
    private int column=0; 
    protected void processCsvFile()
      Recipient resp=null;
      BufferedReader reader=null;
      try {
        File  file=new File("report.csv");
        if(!file.exists())
         return;      
        System.out.println("Reading report.cvs file...");
        reader= new BufferedReader(new FileReader(file));
        StreamTokenizer parser = new StreamTokenizer(reader);
        parser.wordChars(' ', ' ');
        parser.wordChars('@', '@');
        parser.wordChars(':', ':');
        parser.wordChars('-', '-');
        parser.wordChars('"', '"');
        parser.eolIsSignificant(true);
        int nxtToken=0;
        while ((nxtToken=parser.nextToken()) != StreamTokenizer.TT_EOF )
          if(nxtToken==StreamTokenizer.TT_EOL)
           column=0;     
           resp=new BouncedEmail();
         if(parser.lineno()>1)
          switch (parser.ttype)
            case StreamTokenizer.TT_NUMBER:
             switch (column)
                case 1:{
                   resp.setCount((int)parser.nval);       
                       column++; break;
               break;
            case StreamTokenizer.TT_WORD:
               switch (column)
                case 0:{                             
                    resp.setEmail(parser.sval);            
                       column++; break;}
                case 2:{
                 String str=parser.sval.replace('"',' ');;
                    resp.setDate(str.trim());     
                       column++;break;}
                case 3:{                  
                 String str=parser.sval.replace('"',' ');;
                    resp.setTime(str.trim());                 
                       column++; break;}
               break;
               default:
             addBounced(resp);
           } catch (IOException e){
               e.printStackTrace();
          }finally{
          try{
              if(reader!=null)
                  reader.close();      
             }catch(IOException ioe){
            ioe.printStackTrace();
      public PasswordAuthentication getPasswordAuthentication(){
        return authentication;
      private boolean searchEmail(MimeMessage msg)
       String criteria=null;
       String str=null;
    try{      
        criteria=(String)props.get(FROM);
        str=(String)msg.getFrom()[0].toString();
        if(criteria!=null && criteria.length()>1 && str!=null && str.length()>1)
         if(doSearch(str,criteria)==BOUNCED)
           return BOUNCED;
       criteria=(String)props.get(SUBJECT);
       str=(String)msg.getSubject();
       if(criteria!=null && criteria.length()>1 && str!=null && str.length()>1)
        if(doSearch(str,criteria)==BOUNCED)
         return BOUNCED;  
      /*criteria=(String)props.get(BODY); 
       Object  o = msg.getContent();
      if (o instanceof String) {
        str=(String)o;   
       } else if (o instanceof Multipart) {
        Multipart mp = (Multipart)o;
        //int count = OutOfMemoryErrormp.getCount();
        //for (int i = 0; i < count; i++)
        //dumpPart(mp.getBodyPart(i));
       } else if (o instanceof InputStream) {
         //System.out.println("--This is just an input stream");
         //InputStream is = (InputStream)o;
         //int c;
         //while ((c = is.read()) != -1)
         //     System.out.write(c);
      if(criteria!=null && criteria.length()>1 && str!=null && str.length()>1)
        if(doSearch(str,criteria)==BOUNCED)
         return BOUNCED; 
    }catch(OutOfMemoryError oome){
        System.out.println("while in searchEmail "+oome);   
        System.out.println("while in searchEmail "+oome.getStackTrace());
        finalize();
        System.exit(0);  
      catch(javax.mail.internet.AddressException ae){}
      catch(NullPointerException npe){}
      catch(Exception ex){
       //ex.printStackTrace();
       ex.getMessage();
      return !BOUNCED;
      //str is the content that you wnat to search and criteria is the 
      //what you are searching for
      //str      -> From, Subject or Body from Message Object
      //criteria -> From, Subject or Body from Prop file 
      private boolean doSearch(String str,String criteria)
      if(str==null || criteria ==null)
         return !BOUNCED;
        StreamTokenizer token=new StreamTokenizer((Reader)new StringReader(criteria));
        StringSearch sch=new StringSearch(str.getBytes());
        token.wordChars(' ', ' ');
        token.wordChars('@', '@');
        token.wordChars(':', ':');
        token.wordChars('-', '-');
        token.wordChars('"', '"');
        token.eolIsSignificant(true);
        int nxtToken=0;
        try{
        while ((nxtToken=token.nextToken()) != StreamTokenizer.TT_EOF )
           if(token.ttype==StreamTokenizer.TT_WORD)
         if(sch.indexOf(token.sval)>-1)
              return BOUNCED;              
          }catch(OutOfMemoryError oome)
             System.out.println("while in doSearch ");
             oome.printStackTrace();
        }catch(IOException ioe){
         ioe.printStackTrace();
        return !BOUNCED;
      public void sendMessage(String to, String subject, String content) throws MessagingException
          MimeMessage msg = new MimeMessage(session);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject);
        msg.setText(content);
        Transport.send(msg);
      private void addBounced(Recipient resp)
        if(resp==null)
         return;        
        if(bounced==null)
             bounced=new TreeMap();
        String email =resp.getEmail();
        if(email==null)
             return;
         if(isExisting(email)==null){    
           bounced.put(email,resp); 
      private String isExisting(String key)
       if(key==null || bounced==null)
        return null;    
      String name=null;
      Iterator itr=bounced.keySet().iterator();
      while(itr.hasNext())
       name=(String)itr.next();
       if(name==null)
          return null;
       if(name.equals(key))
        return name;
      return null;
    private void writeReport()
      if(bounced==null)
           return;
      Recipient resp=null;  
      File file =null;
       try{
      if(out==null) //writing for to file for the first time
        file=new File("report.csv");
        if(file.exists())
         System.out.println("Found and deleted report file "+file.delete());
         file =new File("report.csv");
         out =new PrintWriter(
              new BufferedWriter(
              new FileWriter(file)),true); 
          out.println("Email,Count,Last Date Bounced,Lasted Time Bounced");    
       Iterator itr=bounced.keySet().iterator();
       String key=null;
       System.out.println("Writing report...");
       while(itr.hasNext())   
        key=(String)itr.next();
        resp=(Recipient)bounced.get(key);
        out.println(key+","+resp.getCount()+",\""+resp.getDate()+"\",\""+resp.getTime()+"\"");     
       }catch(Exception ex){
        ex.printStackTrace();
       }finally{
        if(bounced!=null)
         bounced.clear();
         bounced=null;
         out.flush();
    private void collectGarbage()
      System.out.println("mem before "+Runtime.getRuntime().freeMemory());
      Runtime.getRuntime().gc();
      System.out.println("mem after "+Runtime.getRuntime().freeMemory());
      System.out.println("Garbage collected");     
    private void createBouncedEmail(String email,String date, String time,int count)
       if(email==null)
        return;
       String name=isExisting(email);
       if(name!=null)
        Recipient res=(Recipient)bounced.get(name);
        bounced.remove(name);             
        int c=res.getCount();
        addBounced(new BouncedEmail(email,res.getDate(),res.getTime(),++c));
       }else  
       addBounced(new BouncedEmail(email,date,time,count));
      public void checkInbox(int mode) throws MessagingException, IOException
       Folder inbox=null;
    //   Store store= null;
       JProgressBar pbar=null;
       JWindow window=null;
       try
        if (mode <0) return;
         boolean show = (mode & SHOW_MESSAGES) > 0;
         boolean clear = (mode & CLEAR_MESSAGES) > 0;
         String action =
          (show ? "Show" : "") +
          (show && clear ? " and " : "") +
          (clear ? "Clear" : "");
         System.out.println("Checking mail on: "+props.getProperty("mail.host"));     
         store = session.getStore();
         System.out.println("Trying to connect to mail server: "+props.getProperty("mail.host"));
         store.connect();    
         System.out.println("Connected on mail server : "+getRequestingSite());    
         Folder root = store.getDefaultFolder();    
         inbox = root.getFolder(INBOX);
         System.out.println("Opening mail folder for Reading");    
         inbox.open(Folder.READ_ONLY);
         Message[] msgs = inbox.getMessages();
         if (msgs.length ==0){
          System.out.println("No messages in inbox");
        for (int cnt = 0; cnt < msgs.length; cnt++)
          MimeMessage msg = (MimeMessage)msgs[cnt];
          System.out.println("Reading msg "+cnt);
         if(searchEmail(msg)==BOUNCED)
          createBouncedEmail(msg.getFrom()[0].toString(),null,null,-1);
         if (show)
             System.out.println("    From: " + msg.getFrom()[0]);
             System.out.println(" Subject: " + msg.getSubject());
             System.out.println(" Content: " + msg.getContent());
         if (clear)
            msg.setFlag(Flags.Flag.DELETED, true);
         if((bounced!=null && bounced.size()==blockSize) || cnt==msgs.length-1)
          writeReport();
         if(cnt%100==0)
            collectGarbage();
        //writeReport();
        //end=new Date().getTime();
        //System.out.println("Time complted: "+new Date());  
        //System.out.println("Time taken to complete: "+new Date(end-start));
       }catch(OutOfMemoryError oome)
             System.out.println("while in checkInbox ");
             oome.printStackTrace(); 
       }catch (AuthenticationFailedException afe){
            afe.printStackTrace();
       }finally{
       if(window!=null)
         window.dispose();
       if(inbox!=null)
        inbox.close(true);
       if(store!=null)
        store.close();
       if(out!=null)
        out.close();
    protected void finalize() 
          try{
               if(out!=null)
      out.close();
               if(store!=null)
      store.close();
      System.out.println("Closing connection...");
          }catch(Exception ex){
          ex.printStackTrace();
    }

    Cross posted
    http://forum.java.sun.com/thread.jsp?thread=429947&forum=4&message=1920034

  • Multiple vs single JVM

    I was working a problem with connection pooling and it was pointed out that to utilize pooling all my workstations would have to be using the same JVM.
    I am not clear how one determines how to use the JVM locally or remotely, or some other way?
    Would anyone have an simple explanation for this and care to share it?
    TIA

    I was working a problem with connection pooling and
    it was pointed out that to utilize pooling all my
    workstations would have to be using the same JVM.Either wrong or phrased poorly.
    Obviously if you are relying of any Java API code and you are using different versions then that is a problem. That is not specific to pooling however. For example you can't use Generics in 1.3 because they didn't exist in 1.3.
    Or alternatively just because a pool is running on one box doesn't mean that a pool needs to run on another box. There is no resource sharing between boxes, so conceptually that is not possible.
    >
    I am not clear how one determines how to use the JVM
    locally or remotely, or some other way?
    That doesn't make much sense.
    A VM runs on a box.
    You don't "use" it remotely. You could VPN via telnet into a box and run the VM on that remote box, but none of that has anything to do with java (it is VPN/telnet.)
    Or you could have a client app and and a server app. But then there are still two VMs, one on each box.

  • JVM out of memory (I want to solve this with out increasing the heap size)

    public ThreeVec findVec(double[] pix_lab,double[][] graphic_labs){
    ThreeVec result = new ThreeVec();
    Vector<Double> diff = new Vector<Double>();
    Vector<Double> tempdiff = new Vector<Double>();
    double d1,d2,d3;
    for(int i=0;i<graphic_labs.length;i++){
    d1 = graphic_labs[0]-pix_lab[0];
    d2 = graphic_labs[i][1]-pix_lab[1];
    d3 = graphic_labs[i][2]-pix_lab[2];
    diff.add(Math.sqrt((d1*d1)+(d2*d2)+(d3*d3)));
    tempdiff.add(Math.sqrt((d1*d1)+(d2*d2)+(d3*d3)));
    Collections.sort(tempdiff);
    int[] vecIdx = new int[3];
    vecIdx[0] = diff.indexOf(tempdiff.elementAt(0));
    vecIdx[1] = diff.indexOf(tempdiff.elementAt(1));
    vecIdx[2] = diff.indexOf(tempdiff.elementAt(2));
    double[][] vecs = new double[3][3];
    vecs[0][0] = (graphic_labs[vecIdx[0]][0]);
    vecs[0][1] = (graphic_labs[vecIdx[0]][1]);
    vecs[0][2] = (graphic_labs[vecIdx[0]][2]);
    vecs[1][0] = (graphic_labs[vecIdx[1]][0]);
    vecs[1][1] = (graphic_labs[vecIdx[1]][1]);
    vecs[1][2] = (graphic_labs[vecIdx[1]][2]);
    vecs[2][0] = (graphic_labs[vecIdx[2]][0]);
    vecs[2][1] = (graphic_labs[vecIdx[2]][1]);
    vecs[2][2] = (graphic_labs[vecIdx[2]][2]);
    Matrix vec_matrix = new Matrix(vecs);
    Matrix vec_mat_inv = vec_matrix.inverse();
    Matrix pix_matrix = new Matrix(1,3);
    pix_matrix.set(0,0,pix_lab[0]);
    pix_matrix.set(0,1,pix_lab[1]);
    pix_matrix.set(0,2,pix_lab[2]);
    Matrix abc = pix_matrix.times(vec_mat_inv);
    result.setVecIdx(vecIdx);
    result.setABC(abc);
    return result;
    Matrix is the class defined in JAMA library.
    I am getting OutOfMemoryError in this method.
    Let me explain. The above method is called from a nested 'for' loop something like the pseudocode below.
    BufferedImage in_graphic = ImageIO.read(graphic);
    for(int j=0;j<in_graphic.getHeight();j++){
    for(int i=0;i<in_graphic.getWidth();i++){
    findVec(param1,param2);
    lengths of param1 and param2 are fixed
    param1's length is always 3
    param2.length is 8 and param2[i] is 3
    I thought that this code is independent of image size but it not. As the image size increases beyond a certain size I am getting OutOfMemoryError. I dont know why am I doing something wrong here. Thanks in advance.

    I know you asked about a memory issue, not a speed issue. But, another slight speed-up would be to compute the square root once, and then put it in both lists:
    diff.add(Math.sqrt((d1*d1)+(d2*d2)+(d3*d3)));
    tempdiff.add(Math.sqrt((d1*d1)+(d2*d2)+(d3*d3)));could be:
    Double distance = Double.valueOf(Math.sqrt((d1*d1)+(d2*d2)+(d3*d3)));
    diff.add(distance);
    tempdiff.add(distance);That not only speeds it up (fewer calculations), but it creates half as many Double objects as your way was creating.
    Autoboxing is slowing you down, too. (The use of Double and the autoboxing will go away if you use ejp's suggestion to use arrays of double. But, you could still compute that value only once.)
    Your Vector<Double> are local variables, anyway. If I'm reading your code correctly, they are each only 8 elements long. If so, that's not the main memory issue. Using an array of double primitives will use a little less memory and will be faster, but I don't think the Vector<Double> is the biggest issue. You aren't storing the references to those Vectors anywhere, so they will be eligible for garbage collection at the end of the method.
    So, I know you said it was pseudocode, but your pseudocode as to how findVec was called didn't even use the return value (the ThreeVec that the method creates). Maybe if you explain better what param1 and param2 are (how they are calculated based on height and width, or other useful information), someone could give you a better suggestion. Also, what's a ThreeVec, anyway?
    Maybe try posting the actual code for your loop, instead of pseudocode. Use the CODE button (above the posting box) to format your code nicely.

  • Running multiple java-apps in single JVM?

    We have about 125 Citrix clients running on 5 Citrix Servers. We are investigating a new very big development project which will cover about 10 main projects with 15 Applications each. The complete project will be written in Java.
    Basically, each module will have it's own JVM. BUt, when each client runs a couple of modules, the servers will surely run out of memory...
    I searched for way's to run different modules within 1 single JVM but it seems to be 'not done', because of 'System.exit()', 'Static Variable' probs to name only 2.
    Any idea's on how to implement this?
    thanks.

    thanks for the reply.
    Yes, I assume the server will run out of memory.
    1) Our citrix servers are consuming about 3/4th of their 4Gb memory capacity without any java_application running.
    2) Each of our 5 Citrix servers has 25 users active
    3) Each JVM takes about 20mb memory
    4) Each user will run at least 3 app's simultaneously
    Abouve results in 3*20=60Mb / user * 25= 1,5Gb memory extra needed.
    Can you give me an example of a Thread.sleep(60000) test_pgm?
    and/or an example for a "classloader" program to launch each app in its ow sandbox (in same JVM)?
    (eventually a link to get more info on this)
    thanks

  • Multiple Standalone Persistence Manager Servers in a single JVM?

    Greetings [Kodo 3.4.1, Oracle9i]
    I am currently working on introducing the Kodo Standalone Persistence
    Manager Server into our architecture. One issue is that our application
    accesses several different databases, each via a separate
    PersistenceManagerFactory. This would mean (I think) that I would need to
    start a separate Standalone PM Server for every database, which would mean
    about 10 different JVMs running, just for the required Standalone PM
    Servers...
    The question... Will it be possible and sensible to run multiple
    "Standalone" Persistence Manager Servers within a single JVM? The idea
    would be for me to write a threaded server, where each of my threads invokes
    kodo.jdbc.runtime.StartPersistenceManagerServer.run(someJDBCConf), where I
    provide a JDBCConfiguration for each database I want to connect to. This
    means that my server will effectively be listening for clients on several
    different ports and accessing several databases all from within the same
    JVM.
    Is this feasible? Anyone with access to the source, can you say that the
    StartPersistenceManagerServer.run() method may be safely run in several
    different threads?
    I suppose another option would be to use the HTTP Persistence Manager Server
    and then simply deploy 10 servlets, one per database... But I'm trying to
    avoid introducing a servlet container into the mix.
    Thanks
    Drew

    Hi Marcus and thanks...
    Yes, I want to use Remote Persistence Managers. Currently we have a 2-Tier
    application, but we need to introduce a 3rd tier to be able to use the
    DataCache. If we don't do this, then each running application will have
    it's own DataCache, which will not "see" changes in other running
    application DataCaches. I have tried to attach a "before" and "after"
    diagram to illustrate...
    Now if we extend this a bit further, and say that instead of just one
    database, our application actually needs to access 10 different databases
    (so 10 different PersistenceManagerFactories and 10 different DataCaches),
    then hopefully it is clear that we would then need 10 separate Standalone
    Persistence Manager Servers. I have attempted to attach another diagram to
    illustrate.
    I don't really want to start up 10 Remote PM servers, I would rather just
    have one server, which brings me back to my original question... Can I run
    them all in a single JVM?
    Cheers and thanks
    Drew

  • Multiple applications on a single JVM

    I was looking at some of the disadvantages of running multiple apps on a single JVM and then I came across this sentence which I donot totally comprehend. I guess somebody here would be able to shed some light
    JVMs tend not to scale well past four processor configurations, which limits the viability of the single-JVM model on larger machines

    It means a single JVM won't take as much advantageof
    an 8 CPU system as multiple JVMs will.Yes I understand the lingual meaning of the sentence,
    what I am struggling with is its semantic meaning.
    Why can't a single JVM take advantage of 8 processor
    r CPU? Are there any limitations associated with a
    single JVM and in case there are what could they be?If I remember correctly the inherent concurrency limitations of JVM prevent it from fully utilizing the processing power of the machine. There is a limitation to the heap size one JVM can have, no. of thread pools that could be supported so multiple JVMs provide additional heap size, multiple thread pools, each corresponding to the application associated with the JVM, thus enabling to use the extra processing power.

  • Uploading large files from applet to servlet throws out of memory error

    I have a java applet that needs to upload files from a client machine
    to a web server using a servlet. the problem i am having is that in
    the current scheme, files larger than 17-20MB throw an out of memory
    error. is there any way we can get around this problem? i will post
    the client and server side code for reference.
    Client Side Code:
    import java.io.*;
    import java.net.*;
    // this class is a client that enables transfer of files from client
    // to server. This client connects to a servlet running on the server
    // and transmits the file.
    public class fileTransferClient
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    // this method transfers the prescribed file to the server.
    // if the destination directory is "", it transfers the file to
    "d:\\".
    //11-21-02 Changes : This method now has a new parameter that
    references the item
    //that is being transferred in the import list.
    public static String transferFile(String srcFileName, String
    destFileName,
    String destDir, int itemID)
    if (destDir.equals(""))
    destDir = "E:\\FTP\\incoming\\";
    // get the fully qualified filename and the mere filename.
    String fqfn = srcFileName;
    String fname =
    fqfn.substring(fqfn.lastIndexOf(File.separator)+1);
    try
    //importTable importer = jbInit.getImportTable();
    // create the file to be uploaded and a connection to
    servlet.
    File fileToUpload = new File(fqfn);
    long fileSize = fileToUpload.length();
    // get last mod of this file.
    // The last mod is sent to the servlet as a header.
    long lastMod = fileToUpload.lastModified();
    String strLastMod = String.valueOf(lastMod);
    URL serverURL = new URL(webadminApplet.strServletURL);
    URLConnection serverCon = serverURL.openConnection();
    // a bunch of connection setup related things.
    serverCon.setDoInput(true);
    serverCon.setDoOutput(true);
    // Don't use a cached version of URL connection.
    serverCon.setUseCaches (false);
    serverCon.setDefaultUseCaches (false);
    // set headers and their values.
    serverCon.setRequestProperty("Content-Type",
    "application/octet-stream");
    serverCon.setRequestProperty("Content-Length",
    Long.toString(fileToUpload.length()));
    serverCon.setRequestProperty(FILENAME_HEADER, destDir +
    destFileName);
    serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
    if (webadminApplet.DEBUG) System.out.println("Connection with
    FTP server established");
    // create file stream and write stream to write file data.
    FileInputStream fis = new FileInputStream(fileToUpload);
    OutputStream os = serverCon.getOutputStream();
    try
    // transfer the file in 4K chunks.
    byte[] buffer = new byte[4096];
    long byteCnt = 0;
    //long percent = 0;
    int newPercent = 0;
    int oldPercent = 0;
    while (true)
    int bytes = fis.read(buffer);
    byteCnt += bytes;
    //11-21-02 :
    //If itemID is greater than -1 this is an import file
    transfer
    //otherwise this is a header graphic file transfer.
    if (itemID > -1)
    newPercent = (int) ((double) byteCnt/ (double)
    fileSize * 100.0);
    int diff = newPercent - oldPercent;
    if (newPercent == 0 || diff >= 20)
    oldPercent = newPercent;
    jbInit.getImportTable().displayFileTransferStatus
    (itemID,
    newPercent);
    if (bytes < 0) break;
    os.write(buffer, 0, bytes);
    os.flush();
    if (webadminApplet.DEBUG) System.out.println("No of bytes
    sent: " + byteCnt);
    finally
    // close related streams.
    os.close();
    fis.close();
    if (webadminApplet.DEBUG) System.out.println("File
    Transmission complete");
    // find out what the servlet has got to say in response.
    BufferedReader reader = new BufferedReader(
    new
    InputStreamReader(serverCon.getInputStream()));
    try
    String line;
    while ((line = reader.readLine()) != null)
    if (webadminApplet.DEBUG) System.out.println(line);
    finally
    // close the reader stream from servlet.
    reader.close();
    } // end of the big try block.
    catch (Exception e)
    System.out.println("Exception during file transfer:\n" + e);
    e.printStackTrace();
    return("FTP failed. See Java Console for Errors.");
    } // end of catch block.
    return("File: " + fname + " successfully transferred.");
    } // end of method transferFile().
    } // end of class fileTransferClient
    Server side code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.net.*;
    // This servlet class acts as an FTP server to enable transfer of
    files
    // from client side.
    public class FtpServerServlet extends HttpServlet
    String ftpDir = "D:\\pub\\FTP\\";
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,
    IOException
    doPost(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse
    resp)
    throws ServletException,
    IOException
    // ### for now enable overwrite by default.
    boolean overwrite = true;
    // get the fileName for this transmission.
    String fileName = req.getHeader(FILENAME_HEADER);
    // also get the last mod of this file.
    String strLastMod = req.getHeader(FILELASTMOD_HEADER);
    String message = "Filename: " + fileName + " saved
    successfully.";
    int status = HttpServletResponse.SC_OK;
    System.out.println("fileName from client: " + fileName);
    // if filename is not specified, complain.
    if (fileName == null)
    message = "Filename not specified";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // open the file stream for the file about to be transferred.
    File uploadedFile = new File(fileName);
    // check if file already exists - and overwrite if necessary.
    if (uploadedFile.exists())
    if (overwrite)
    // delete the file.
    uploadedFile.delete();
    // ensure the directory is writable - and a new file may be
    created.
    if (!uploadedFile.createNewFile())
    message = "Unable to create file on server. FTP failed.";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // get the necessary streams for file creation.
    FileOutputStream fos = new FileOutputStream(uploadedFile);
    InputStream is = req.getInputStream();
    try
    // create a buffer. 4K!
    byte[] buffer = new byte[4096];
    // read from input stream and write to file stream.
    int byteCnt = 0;
    while (true)
    int bytes = is.read(buffer);
    if (bytes < 0) break;
    byteCnt += bytes;
    // System.out.println(buffer);
    fos.write(buffer, 0, bytes);
    // flush the stream.
    fos.flush();
    } // end of try block.
    finally
    is.close();
    fos.close();
    // set last mod date for this file.
    uploadedFile.setLastModified((new
    Long(strLastMod)).longValue());
    } // end of finally block.
    } // end - the new file may be created on server.
    } // end - we have a valid filename.
    // set response headers.
    resp.setContentType("text/plain");
    resp.setStatus(status);
    if (status != HttpServletResponse.SC_OK)
    getServletContext().log("ERROR: " + message);
    // get output stream.
    PrintWriter out = resp.getWriter();
    out.println(message);
    } // end of doPost().
    } // end of class FtpServerServlet

    OK - the problem you describe is definitely what's giving you grief.
    The workaround is to use a socket connection and send your own request headers, with the content length filled in. You may have to multi-part mime encode the stream on its way out as well (I'm not about that...).
    You can use the following:
    http://porsche.cis.udel.edu:8080/cis479/lectures/slides-04/slide-02.html
    on your server to get a feel for the format that the request headers need to take.
    - Kevin
    I get the out of Memory Error on the client side. I
    was told that this might be a bug in the URLConnection
    class implementation that basically it wont know the
    content length until all the data has been written to
    the output stream, so it uses an in memory buffer to
    store the data which basically causes memory issues..
    do you think there might be a workaround of any kind..
    or maybe a way that the buffer might be flushed after
    a certain size of file has been uploaded.. ?? do you
    have any ideas?

  • Out of memory error in IBM JVM

    Hi i am using websphere application server's dyna cache for getting performance optimiztion in my application.
    I am able to load values into the cache using the command cache api in the dyna cache.When i clear the cache for loading another set of values the cache gets cleared but still ,while loading the second set of values i get an out of memory error
    The dynacache is an distributed map
    i want to know whether the error is due to improper garbage collection
    on this map,if so help me to overcome this
    The JVM configuration are as follows
    Min 256mb
    Max 768mb
    I have a total of 1Gb ram

    Maybe your program's memory usage is rubbing against the upper limit, and something about the latest JVM caused it to break through.
    Try using the command line parameter -mx500m (for 500 megs or whatever amount you neeed)

  • JVM and out of memory error

    i am getting a memory out of error when i run an application.But the tomcat(which is running as a service) is not restarting.
    both the applicationa are using the same JVM, but the memory out of error is not affecting the tomcat y?

    What I need is help, not you telling me this. Are you
    an administrator or something?It should be obvious from his post count that
    he is not an admin or mod (they tend to not post)
    but one of the regulars who try to help people...
    Why can't we use others' thread?Because it confuses the issue.
    I appreciate everyone's help given to me and like this
    academic environment very much until the emergence of you!How myopic to berate someone for informing you how best to get help.

  • Importing a single track results in "Out of Memory!"

    I'm trying to import an audio track from another session into my current song, and Logic gives me "Out of Memory! Couldn't insert or delete data".
    I have 24 gigs on this system, and 12 currently free. I'm running Logic in 64-bit.
    What the heck is going on???

    Gowtam,
    Are you sure that the HashMap object is available for GC at the end of your controller code?
    If your JVM Heap is relatively small compared to the size of your HashMap, then you can hit this issue. Analyze, if you really require such a huge collection on objects to work on, if there is no other alternative, then go ahead and do a memory turning to find out the optimum memory requirement / user and tune your JVM accordingly.

  • Prevent jvm shut down by user + Out of memory

    HI all
    i have a problem,i have a suspect that one of my customer shut down jvm with Task Manager(Windows XP).
    Is possible to block the shotting down operation?
    Another question is possible to catch an out of memory (i doesn't know when and where is generated) and show it at the user?
    Thanks!!

    This link should answer your question regarding catching an OutOfMemory error.
    http://www.onjava.com/pub/a/onjava/2001/08/22/optimization.html

  • Multiple web apps sharing same cache in a single JVM ?

    Is it possible to share cache across multiple web apps running in the same app server (multiple web apps, single JVM) ?
    Thanks for any info.

    Hi Bob,
    Cluster membership is scoped to the ClassLoader, so if your application server provides a ClassLoader-per-application, this will work fine.
    This is supported for both Coherence (NamedCaches) and Coherence*Web (HTTP sessions).
    Jon Purdy
    Tangosol, Inc.

  • Multiple RMI servers in single JVM

    Hi,
    I have a RMI server listening to requests from internal network as well as external network. RMI returns the hostname as part of the stub. So to ensure that the subsequent RMI calls work fine I need to ensure that jama.rmi.hostname is set to correct value.
    With 2 network IPs on 1 machine (internal & external), one option was to use a domain name as hostname and set it as java.rmi.hostname. Unfortunately, my client is not allowing use of DNS. So the hostname can be set only as an IP address.
    Is there some way I can start 2 RMI servers in single JVM. While starting first one I can set hostname as internal IP and then while starting the other one I set hostname as external IP.
    Problem is I don't know if such a solution can be setup. I read somewhere that from jdk1.4, System.setProperty("java.rmi.server.hostname", "172.25.17.41"); will set hostname dynamically. So all future requests will use the latest hostname.
    Important thing is some way to make sure both networks can connect to my JVM through RMI.

    I get it, you're going down the path I hate. I have undone this so many times ... (essential when deploying RMI Proxies).
    Don't know why your intranet clients can't connect, unless it's the local binding of the server socket.
    If you must explore this horrible kludge around a Sun kludge (and overload the SF mechanism even further), you may as well go the whole hog and have the SSF corresponding to each CSF bind its ServerSocket to the local address that you're going to embed in the CSF. Then you really know who can connect and who can't.
    When writing SFs you need to think about what equality of socket factories really means. It only needs to imply that both socket factories being compared observe the same superimposed protocol (e.g. SSL), or that they both don't superimpose a protocol at all, so outbound or incoming calls really really can share the same port.
    SF equality generally doesn't need to extend as far as whether the embedded host names (in your case - ugh!) are the same, or the port numbers if you want go the whole hog and bypass the stub's remote reference info altogether.

  • General Error and Out of Memory Error - affecting multiple projects

    I am running Final Cut Pro 6 on my 1.25 GHz PowerPC G4 iMac, with 1.25 GB RAM. OS X 10.4.11.
    I have had this setup for more than a year and used it without any problems.
    I have two projects stored on an external LaCie firewire drive with more than 140GB disk space remaining. As of this morning, I cannot work on either of them: both are throwing the "General Error" message, and one of them is also telling me it's "Out of Memory". On project #1, the "Out of Memory" occurs whenever I try to open a clip in the viewer, following a "General Error" message. On project #2, the "General Error" message occurs when I try to open the project; it gets halfway through the process and then throws the error, leaving me unable to open the timeline.
    Both projects are short, less than 3 minutes long, and neither project contains any CMYK or grayscale graphics. Project #2 does have a short Motion sequence.
    Things I have tried:
    ~ restarting and hard-rebooting
    ~ trashing preferences
    ~ rebuilding permissions
    ~ trashing render files
    ~ creating a new project
    ~ searching this forum and Google for other answers
    Help?

    Thanks for the support, Jim. I've had terrible experiences with Firewire drives in the past, too; regrettably, there doesn't seem to be an affordable alternative at this point.
    I just looked up resetting the PMU, as that's not something I've done before. I really hope it's that simple, as the thought of recreating all these clips makes my head hurt. But I'll definitely try your suggestion of reconnecting individual media files first. I've been through that before.

Maybe you are looking for

  • Error 7 with Report Generation Toolkit

    Hello Everyone, I'm trying to generate an Excel sheet report for some readings using "Report Generation toolkit" But when trying to generate the report, the report generation part of code is executed and gives Error(7) and there is no report is gener

  • Creative Cloud Licence status issue

    Hi, We've been using Creative Cloud for almost a year, no issues other than when we first set it up and had an out of data Creative Cloud admin tool which kept telling us we had to register within 15 days or lose access.  An upgrade was downloaded an

  • What is a WEP key and where do I find it?

    Any dumbed down help would be greatly appreciated because I'm close to returning the base station time capsule thing. I can connect macs because I know the password, but friends with PCs can't connect, I can't connect a netbook or a blackberry becaus

  • Floppy disk cassette

    Can I get a USB adapter for the connector on my IBM 600e floppy disk cassette?   I would like to be able to use this cassette on a Dell laptop

  • Hi, I have just downloaded lion and my Photoshop CS is not supported.....why why why. This update will cost me $500 ! Totally useless update

    I have just downloaded LION as an update and it is OK, not great but OK. However I am furious because it does not support Photoshop CS for Mac! Great so this update is now going to cost me 500 dollars for a new Photoshop. Well done Apple why is this