This byte array is not garbage collected?

imageBytes[] does not seem to ever be garbage collected. I've pinpointed a SINGLE LINE that, when commented out, will prevent the memory leak. What could possibly be wrong with this line?
Running this code results in a "OutOfMemoryError: Java heap space" after roughly a minute on my machine. I'm using JRE version 1.5.0_08.
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
// creates images to send to ImageConsumer
public class ImageProducer {
     static BufferedImage bufferedImage;
     static Robot robo;
     static byte[] imageBytes;
     public static void main(String args[]) {
          try {
               robo = new Robot();
          } catch(Exception e) {
               e.printStackTrace();
          PipedOutputStream pos = new PipedOutputStream();
          new ImageConsumer(pos).start();
          bufferedImage = robo.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
          try {
               ObjectOutputStream oostream = new ObjectOutputStream(pos);
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               ImageIO.write(bufferedImage, "JPG", baos);
               baos.flush();
               imageBytes = baos.toByteArray();
               while (true) {
                    ImageIO.write(bufferedImage, "JPG", baos);
                    baos.flush();
                    // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
                    // If you comment the following line out, there will be no
                    // memory leak. Why?  I ask that you help me solve this.
                    imageBytes = baos.toByteArray();
                    baos.reset();
                    oostream.writeObject(imageBytes);
                    pos.flush();
          } catch (Exception e) {
               e.printStackTrace();
// This thread reads the image data into bImg
class ImageConsumer extends Thread {
     BufferedImage bImg;
     PipedInputStream pis;
     ImageConsumer(PipedOutputStream pos) {
          try {
               pis = new PipedInputStream(pos);
          } catch (IOException e) { e.printStackTrace();}
     public void run() {
          try {
               ObjectInputStream oinstream = new ObjectInputStream(pis);
               while (true) {
                    byte[] imageBytes = (byte[])oinstream.readObject();
                    ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
                    bImg = ImageIO.read(bais);
          } catch (Exception e) {e.printStackTrace();}
}

while (true) {
     ImageIO.write(bufferedImage, "JPG", baos);
     baos.flush();
     // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
     // If you comment the following line out, there will be no
     // memory leak. Why? I ask that you help me solve this.
     imageBytes = baos.toByteArray();
     baos.reset();
     oostream.writeObject(imageBytes);
     pos.flush();
}I have only briefly gone through the code, but why are you flushing it right before calling that line. Won't the byte array returned always be empty right after flushing the stream?

Similar Messages

  • WLS not garbage collecting enough?

    WLS 5.1 SP5
    SunOS 5.6 (2.6)
    JDK 1.2.2_005a (with the JVMARGS directive set as per BEA's docs. The
    JVMARGS directive solved the SIGBUS 10 for us when requesting the
    AdminMain servlet)
    We tried some stress testing of our web app by running about 100 to 200
    virtual clients requesting the same URL (servlet that forwards to a
    JSP). These virtual clients are actually Java threads running
    simultaneously.
    After each test, we notice that, via WL console, the heap usage of WL
    increased. However, after leaving WL server by itself (no HTTP requests
    coming to it) for a long time (say 30 minutes to 1 hour), we noticed
    that the heap usage has not gone down, except for about 1%. As soon as
    we explicitly tell WLS to garbage collect via the WL console, then the
    heap usage goes down ... sometimes even as low as just 10% when we tell
    it to gc again just after a gc a few seconds earlier.
    Is this proper behaviour by WLS? ... or does this have something to do
    with the JVMARGS directive? Why doesn't it gc even after a long time?
    Thanks in advance,
    John Salvo
    Homepage: http://homepages.tig.com.au/~jmsalvo/

    There are a number of problems with memory usage and garbage collection. Going to WLS 5.1 will fix
    some of them. You should also consider having your application call System.runFinalization(); and
    System.gc() from time to time.
    Mike
    "Jim Zhou" <[email protected]> wrote:
    I see the same behavior in my stress test/pre-production run. I think it's
    normal behavior. The GC will kick in when the heap size gets 100%, you might
    see a pause in your WLS because all threads will stop for the GC ( you
    should see CPU really busy when GC is in ). JDK 1.2 should have better GC
    algorithm than JDK 1.1. Usually for people still using JDK1.1.x, tuning the
    heap size for tolerable GC pause is a pain., the tuning guide want you to
    run multiple WLS instances in a box to stagger the effects of GC pause. If
    you use JDK 1.2, you probably set your heap size comparable to your box's
    memory.
    In one of my stress test, I set heap size to 256m, I see on my console the
    heap gets full every 30 seconds, and it take 1 or 2 seconds to GC. But if
    your heap is 2G, it might take longer.
    WLS 4.51 SP11
    Solaris 2.6
    JDK 1.2.2_06.
    Regards,
    Jim Zhou.
    Jesus M. Salvo Jr. <[email protected]> wrote in message
    news:[email protected]...
    WLS 5.1 SP5
    SunOS 5.6 (2.6)
    JDK 1.2.2_005a (with the JVMARGS directive set as per BEA's docs. The
    JVMARGS directive solved the SIGBUS 10 for us when requesting the
    AdminMain servlet)
    We tried some stress testing of our web app by running about 100 to 200
    virtual clients requesting the same URL (servlet that forwards to a
    JSP). These virtual clients are actually Java threads running
    simultaneously.
    After each test, we notice that, via WL console, the heap usage of WL
    increased. However, after leaving WL server by itself (no HTTP requests
    coming to it) for a long time (say 30 minutes to 1 hour), we noticed
    that the heap usage has not gone down, except for about 1%. As soon as
    we explicitly tell WLS to garbage collect via the WL console, then the
    heap usage goes down ... sometimes even as low as just 10% when we tell
    it to gc again just after a gc a few seconds earlier.
    Is this proper behaviour by WLS? ... or does this have something to do
    with the JVMARGS directive? Why doesn't it gc even after a long time?
    Thanks in advance,
    John Salvo
    Homepage: http://homepages.tig.com.au/~jmsalvo/

  • All Tweens randomly halting (Not Garbage Collection)

    I am developing a game with some AS3 tweens. I have encountered the problem of garbage collection affecting tweens before so I have all my tweens referenced at the class level now to ensure that isn't a problem. However, randomly all the current tweens in my game will stop. Other, non-tweened, frame by frame animations continue. It's just like the garbage collection problem but the tweens shouldn't be being collected...
    The code I am using for tweens:
    Var declaration at the top of the class:
    private var gateTween:Tween;
    This code in a function:
    gateTween = new Tween(currentGate, "x", None.easeOut, 800, 380, 1.5, true);
    gateTween.addEventListener(TweenEvent.MOTION_FINISH, horseJump);
    Any ideas would be appriciated.

    I have Swing based java project. Im setting all the
    references to null as and when i dont need them, and
    then im calling System.gc() also.
    However it seems the memory is not being released,
    when i check in the task manager, memory usage does
    not reduce. It seems garbage collection is not
    happening.Actually I have a small class - where in I try to do this:-
    public class TestDebug extends Object{
    /** Creates a new instance of TestDebug */
    public TestDebug() {
    * @param args the command line arguments
    public static void main(String[] args) {
    System.out.println("Trying to debug this");
    TestDebug testDebug = new TestDebug();
    testDebug.finalize();
    System.out.println("Lasting print");
    public void finalize(){
    System.out.println("Finalize called");
    System.gc();
    System.out.println("Finalize finished");
    But it is also true that you should never try to force it - It has its own way to do it.
    For Example try to execute a big code(so that you can find JVM doing the GC) as "java -verbose:gc class-name"
    You will find at some points during the execution process - that the JVM actually runs the GC on its own- but when not that is not defined.It is a low priority thread running under JVM.

  • URL class is not being garbage collected

    I have created two instances of the URL class to specify a file location for each image. I use com.symantec.itools.javax.swing.icons.ImageIcon class to display images specified by each URL instance as icons inside a button. The setImageLocation method(URL location) of the ImageIcon class sets the location to be displayed by this icon. The following is the code snippets used to create the ImageIcon instances:
    private URL greenIconURL;
    private URL redIconURL;
    com.symantec.itools.javax.swing.icons.ImageIcon green_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    com.symantec.itools.javax.swing.icons.ImageIcon red_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    try
    greenIconURL = new java.net.URL
    ("file:./images/greenline.gif");
    green_icon.setImageLocation(greenIconURL);
    catch (java.net.MalformedURLException error) { }
    try
    redIconURL = new java.net.URL
    ("file:./images/redline.gif");
    red_icon.setImageLocation(redIconURL);
    catch (java.net.MalformedURLException error) { }
    I am using JProbe 5.0.1 Memory to determine the loitering objects when I remove the button from the JInternalFrame. I am using Java 1.2.2_08 version. The JProbe Memory Leak Doctor indicates that each URL instance has a reference to an entry in a HashMap table. The reference graph from the root set has a reference to SoftCache to HashMap to HashMap$Entry. To make this URL instance eligible for garbage collection, JProbe Memory Leak Doctor indicates I must remove the entry from the HashMap. How do I get access to this HashMap to remove the entry? If this is a problem with the version of the JDK, please let me know. Thank you in advance for your assistance.

    <root>Statics
    -->sun.misc.SoftCache->java.util.HashMap->java.util.Has
    Map$Entry[]->java.util.HashMap$Entry->java.net.URL
    I do not an instance of HashMap in my class.
    Therefore, the HashMap is either created by URLclass
    or the
    com.symantec.itools.javax.swing.icons.ImageIcon
    class.SoftCache seems to have a normal HashMap inside
    it/* Hash table mapping keys to ValueCells */
    private Map hash;but if that is the HashMap in JProbe
    information then the URL would have to be a key in
    the map - otherwise there'd be another object in the
    chain of class SoftCache.ValueCell
    are you certain that the java.net.URL's in that
    hashmap are your ones?
    out of curiosity - are you certain that the URL's are
    the/a problem (are you getting an OutOfMemoryError?)
    asjfThe button that contains the URL's is the only one on the JInternalFrame. The JProbe Memory Debugger displays the java.net package name, the URL class name, the count (2), and the Count Change (+2). When I remove the button from the JInternalFrame, the aforementioned numbers on the Instance Summary remain the same. The snapshot of the Java Heap reveals that the two instances of the URL class are still there. The Memory Leak Doctor shows the reference graph from the root set:
    <root>Statics->SoftCache->HashMap->HashMap$Entry[]->HashMap$Entry->URL
    When I right click on the arrow between HashMap$Entry[] and HashMap$Entry to remove the reference, I receive the message: "Congratulations this object can be garbage collected..." It appears like private instance of Map in SoftCache is holding a strong reference.
    I am not getting an OutOfMemoryError exception.

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • Problem in reading/writing byte array in Access database! PLEASE HELP!!

    Hi,
    I want to store a signature, which is in form of a byte array, in OLE Object field in MS Access database. I want then to retrieve this signature and verify it. The problem is that the retrieved byte array is not identical to the stored (original) one, and therefore, verifying the signature fails! Any help would be much appreciated as I can't proceed in my project without solving this problem. Here is the code to do the above mentioned functionality:
    //This part stores the signature (VT) in the table TTPTrans
    try
    { con = connect();
    ps = con.prepareStatement("UPDATE TTPTrans SET VT = ?, SigVT = ? WHERE TransID = ?");
    ps.setBinaryStream(1, new ByteArrayInputStream(vt), vt.length);
    ps.setBinaryStream(2, new ByteArrayInputStream(sigvt), sigvt.length);
    ps.setString(3, tID);
    ps.executeUpdate();
    ps.close();
    con.close();
    catch (Exception e)
    {  System.err.println(e.getMessage());
    e.printStackTrace();
    //This part retrive the signature from the table in the byte array o1:
    ResultSet result;
    byte[] o1 = null;
    byte[] o2 = null;
    try
    { con = connect();
    Statement statement = con.createStatement();
    result = statement.executeQuery("SELECT VT, SigVT" +
    " FROM TTPTrans" +
    " WHERE TransID = " + "'" +
    transID + "'");
    while (result.next()) {
    o1 = result.getBytes("VT");
    o2 = result.getBytes("SigVT");
    statement.close();
    con.close();
    catch(Exception e)
    { System.err.println(e.getMessage());
    e.printStackTrace();
    }

    In the following code, I use a ASN1SDSSSignature class, which is a subclass that I created from the Siganture class, to create and verify an SDSS signature. The ASN1SDSSSignature has two ASN1Integer class variables:
    signcryption = token.getSigncryption();
    sig.initVerify(ttpCert);
    sig.update(receivedVT);
    boolean verified = sig.verify(receivedSigVT);
    if(!verified)
    System.err.println("TTP signatire on received token invalid. ");
    notify()
    return;
    Where receivedVT and receivedSigVT are the byte arrays retrieved from th database. The following exception is thrown when I run the application:
    ASN1 type mismatch!
    Expected: codec.asn1.ASN1Integer
    In: ASN1SDSSSignature
    At index 0
    Got tag: 4 and Class: 0
    I hope this would clarify the situation and thanks in advance for any comments you may post.

  • Problem with string constructor when using byte array as parameter

    I am creating a string using constructor and passing byte array as parameter.This byte array i am getting from MessageDigest's digest() method,i.e. a hash value.
    The problem is when i iterate through byte array i can able to print all the values in byte array.But when i construct a string from that byte array and printing that string ,that is printing some unknown characters.
    I don't know whether i need to pass charsequence to the constructor and the type of charsequence.Can anybody help me?
    Thanks in advance

    Is there some problem today? I'm getting this sort of thing all over.
    I already told you and so did Kayaman. Don't. String is not a holder for binary data. You have to Base-64 encode it. If you don't you cannot reconstruct the original binary digest value, so putting it into a database is completely utterly and entirely pointless.
    Is that clear enough?

  • Garbage collection Java Virtual Machine : Hewlett-Packard Hotspot release 1.3.1.01

    "Hi,
    I try and understand the mechanism of garbage collection of the Java Virtual Machine : Hewlett-Packard Hotspot release 1.3.1.01.
    There is description of this mechanism in the pdf file : "memory management and garbage collection" available at the paragraph "Java performance tuning tutorial" at the page :
    http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,1607,00.html
    Regarding my question :
    Below is an extract of the log file of garbage collections. This extract has 2 consecutive garbage collections.
    (each begins with "<GC:").
    <GC: 1 387875.630047 554 1258496 1 161087488 0 161087488 20119552 0 20119552
    334758064 238778016 335544320
    46294096 46294096 46399488 5.319209 >
    <GC: 5 387926.615209 555 1258496 1 161087488 0 161087488 0 0 20119552
    240036512 242217264 335544320
    46317184 46317184 46399488 5.206192 >
    There are 2 "full garbage collections", one of reason "1" and one of reason "5".
    For the first one "Old generation After " =238778016
    For the second "Old generation After " =238778016
    Thus, "Old generation Before garbage collection" of the second is higher than "Old generation After garbage collection". Why?
    I expected all objects to be allocated in the "Eden" space. And therefore I did not expect to s

    I agree but my current Hp support is not very good on JVM issues.
    Rob Woollen <[email protected]> wrote:
    You'd probably be better off asking this question to HP.
    -- Rob
    Martial wrote:
    The object of this mail is the Hewlett-Packard 1.3.1.01 Hotspot JavaVirtual Machine
    release and its garbage collection mechanism.
    I am interested in the "-Xverbosegc" option for garbage collectionmonitoring.
    I have been through the online document :
    http://www.hp.com/products1/unix/java/infolibrary/prog_guide/java1_3/hotspot.html#-Xverbosegc
    I would like to find out more about the garbage collection mechanismand need
    further information to understand the result of the log file generatedwith the
    "-Xverbosegc"
    For example here is an extract of a garbage collection log file generatedwith
    Hewlett-Packard Hotspot Java Virtual Machine. Release 1.3.1.01.
    These are 2 consecutive rows of the files :
    <GC: 5 385565.750251 543 48 1 161087488 0 161087488 0 0 20119552 264184480255179792
    335544320 46118384 46118384 46137344 5.514721 >
    <GC: 1 385876.530728 544 1258496 1 161087488 0 161087488 20119552 020119552 334969696
    255530640 335544320 46121664 46106304 46137344 6.768760 >
    We have 2 full garbage collections, one of Reason 5 and the next oneof Reason
    1.
    What happened between these 2 garbage collections as we got : "Oldgeneration
    After" of row 2 is higher than "Old generation Before" of row 1? Iexpected Objects
    to be initially allocated in eden and so we could not get "old generation2modified
    between the end of one garbage collection and before the next one.
    Could you please clarify this issue and/or give more information aboutgarbage
    collection mechanisms with the Hewlett-Packard Hotspot Java VirtualMachine. Release
    1.3.1.01.

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • Writing empty byte array to outputstream

    Does anyone know if writing an empty byte array to an outputstream will throw an IOException? I think a little bug in my code is causing this because all seems to work when the byte array is not empty.
    Thanks in advance for any help.

    The (overridden) method write(byte[]) of java.io.OutputStream throws a java.lang.NullPointerException rather than java.io.IOException when byte[] is simply null.

  • How Convert a Byte array to a image format

    Hi,
    How to convert a Byte array to an image format....I shall be more clear what i want...See i recieve a Byte array fom server this Byte array before recieveing at my end it was converted from an image/text format into a Byte array and is sent from server and, I recieve this Byte array now I have to convert this Byte array into their respective image....please tell me how to convert a Byte array to a image ......... Kindly explain clearly as i am new to Java......
    Thanking You.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • Another question?? being able to send byte arrays containing multiple types

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{ 
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but rather just create one object and be able to send and receive the information on both ends
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    which forum should I be posting this on?Serialization.
    To get you started...
    public class O_struct implements Serializable {                                                                                                                                                                                                                                                                                   

  • Full Garbage Collection

    Hi Friends,
    I'm using weblogic workflow for my project. Last night i got one error, once i gone throw the bea ...i come to know that the error will comes because of "once the application calls webservice and the webservice intern calls the EJB stateless or stateful will fail". But my application is not using any sort of webservices. So i try to find the problem finally i found tht the problem is because of Garbage collection of Heap Size. It is taking 3.8508577 sec's. I feel in this time the JVM thread gets heighest priority and it is killing the application thread which is to be executed as usal.
    Can u guide me how to catch this exception so tht my application won;t get affected. The actual error says like this which is related to Garbage Collection...[Full GC 313152K -> 105060K (1004928K), 3.8508577 secs]. I'm using JDK 1.4.
    Thaks & Regards
    [email protected]

    Replies in this thread.

  • Garbage Collection and Constant CPU Usage

    Hello,
    We have a load balanced environment running ColdFusion 10 Enterprise with 5 instances currently running. Currently we only have one instance being actively used but have been encountering a problem within a time frame of 12 to 36 hours (calculated on the times we have had to restart CF to come back online) the garbage collection is running almost constantly and CPU holds at 50% until the server just becomes unresponsive until the CF instance is restarted.
    I have been monitoring the server via VisualVM to watch the CPU and Heap usage since I have found that running the server monitoring systems build into CF 10 Enterprise accelerate the problem to cause a crash within 4 to 5 hours.
    This issue has been occuring regardless if there is heavy load or not on the server. I have been seeing some odd behaviour when running CF Stat where I am seeing 4 Requests Queued and Running Requests never shows anything other than 0. I increased the Minimum Heap Size to 512 MB and Maximum Heap Size to 1024 MB and below is our JVM arguments
    -server -XX:MaxPermSize=192m -XX:+UseParallelGC -Xbatch -Dcoldfusion.home={application.home} -Dcoldfusion.rootDir={application.home} -Dcoldfusion.libPath={application.home}/lib -Dorg.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER=true -Dcoldfusion.jsafe.defaultalgo=FIPS186Random -Dcom.sun.management.jmxremote.port=8701 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
    We are running on a Windows 2008 64 Bit and IIS 7.5 on both of the load balanced servers and have updated the server to ColdFusion 10 Update 2. I am aware of the issues that are being fixed in Update 3 that was removed last week by Adobe due to bugs introduced.
    If anyone has any insight in how to fix this issue, I would be greatly appreciative.  This is affecting a production server that did not show these problems when we put the servers under load when we did pre launch settings.

    Further from your images - while it shows CF CPU at 50% the GC activity is 0%.
    So could be your not garbage collecting more than necessary and something else CF wise is taking CPU time.
    What would be interesting is the Jconsole Memory tab Details section. It shows the time spent in minor and major GC's.  eg:
    HTH, Carl.

  • Confusion regarding Binary data and byte arrays

    HI guys,
    I have a question...i am going to send some binary data...the format of that data is that first two bytes is the lenght of the data and then follows that data. Here i have one confusion. e.g. i want to say that the lenght of my data is 1000 bytes. How do i do it.
    coz if i do something like this.
    int k = 1000;//the length of my data
    String binaryString = Integer.toBinaryString(k);
    byte[] binaryData = binaryString.getBytes();
    and then if i say binaryData.lenght, i see a lenght of 10, as the binary string which
    is generated is -> 1111101000. i guess its obivious as this byte array is nothing but perhaps a character array with each character occupying one thread...so what exactly is the difference between byte array and binary data. and in the above said condition how do i send the binary data?
    Also adding to my confusion is the fact that i have a file which contains binary data, but that data is not 10010101 type of data...its just some absurd characters. How do we explain this.
    i would be highly grateful if you could explain me the solution to this problem.
    I am not getting as to how to go about it.
    its urgent..pls help...

    one sec..actually i dont want to 'read' the two bytes. That i know how to do? but The thing is that i want to write a binary stream. right? so in that the first two bytes should be the size of the data, followed by the data itself. So i want to write the first two bytes, which should contain the size of data (as a matter of fact i have that binary data in a byte array). But my question is , that if i say the size of data is 1000 (bytes , since, as i said i am gettting the data as a byte array), how do i write this in my binary stream as 1000 in this case would be an int. right? which is four bytes. So essentially that byte array (which contains binary data) i have to forward to somewhere, say X , but X reads binary data in the following way...it expects the first two bytes to give him info regarding the size of the data to follow and then it starts reading the data from the third byte onwards till the size of the data (which it got by reading first two bytes)...i hope i could communicate my confusion better this time

Maybe you are looking for

  • Mixing RAM Modules

    Several weeks ago, I replaced my 256 MB RAMs with 2 1 GB modules in a late 2005 G5. They seemed to work fine, though my GPU seemed to be running a bit hotter. I just installed an additional 2 GB bought from OWC, and also added back the 2 original 256

  • Locating Adobe PDF resource files-steps.

    Unable to find "Adobe PDF" resource file, please help.

  • Where to activate xsplit?

    Hi, just got a MSI GTX 980 GAMING 4G graphics card in christmas but i have been trouble on activating my xsplit :/ it gave me a 6 month free premium to it but i already had an account before it but thing is i have looked everywhere for where to activ

  • In DEV client i have to copy controlling area or i mantain controlling area

    Hi in DEV client i have to copy controlling area or i mantain controlling area which is preferable.

  • How to view list buffer in new debugger?

    Hi there, Any body knows how to view the list buffer generated so far while debugging in new debugger.It says, after first write statement a new button appears in tool bar.I couldn't find it.Please help. regards