Finalizer class

Dear All,
I have some question about Java as OO - programming language especially in UML. I've try to do code generation. I found out the tool support method 'finalizer'(consider as special method for destruction of class). Can anyone tell me whether there is any finalizer method available?
Thank you,
Tan

Try this link:
http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44748

Similar Messages

  • Finalize Memory Issues (A Horrible Lesson)

    Im working on a project where I have to create and analyze an insane number of binary trees.
    The program takes a node size and when n=13 it makes 700,000 trees and when
    n=16 it makes over 30 million.
    I know that with 2gb of ram I could do n=16 because 2 days ago I ran it successfully.
    However, yesterday I could barely run n=13.
    After 6 hours of frustration the netbeans memory profiler gave some insight.
    I had overridden the finalize method yesterday with only an integer increment (to track node creation as part of the project).
    public class Node{
    public void finalize(){
    FINALIZED++;
    static int FINALIZED;
    }Netbeans Memory Snapshot:
    java.lang.ref.Finalizer ... live objects ~10 million ... 330 MB
    project.Node ... live objects ~10 million ... 220 MB
    Object[] ... live objects 3 ... 50 MB
    project.Node is my class and comes to about 24 bytes per object which is about right (it hold 3 references and a byte).
    the Object[] are the 3 arrays holding my trees.
    But where did this "Finalizer" class come from? It has a lot of overhead (relative to my object).
    final class Finalizer extends FinalReference {
        static private ReferenceQueue queue = new ReferenceQueue();
        static private Finalizer unfinalized = null;
        static private Object lock = new Object();
    public class ReferenceQueue<T> {
        private Lock lock = new Lock();
        private Reference<? extends T> head = null;
        private long queueLength = 0;Apparently, overriding the finalize method creates a Finalizer object?
    Why would overriding a method create this new object?
    Can anyone clear up what is going on?

    jschell wrote:
    You already know that you have one for each live object.
    The only point of using finalize is for GC. So it must be adding that for use by the GC.
    Other than that most of what the VM does is done by java. This is just some more functionality in terms of that.
    If you want to know specifically what it does you can ask in the JVM forum (I believe a vm implementor frequents that forum) or dig into the source yourself.You are right. That is all there is to it.
    I took a free moment and wrote a demo class and learned how to insert a profile point in NetBeans.
    My results are:
    java.lang.ref.Finalizer ... instances: 500,014 ... size: 16,000,448 ... (32 bytes each)
    memtest.Main ... instances: 500,000 ... size: 8,000,000 ... (16 bytes each)
    When you override finalize() you add a 32 byte overhead per object.
    Matter resolved! Thanks.
    import java.util.*;
    public class Main {
    public static void main(String[] args){
         int size = 500000;
         List list = new ArrayList(size);
         Random r = new Random();
         for(int i = 0; i < size; i++){
         list.add(new Main(r.nextLong()));
         // insert heap dump profiling point
         System.out.println("list size: " + list.size());
    public Main(long number){
         this.number = number;
    public void finalize(){
         count++; 
         long number;
         static int count;
    }

  • Being specific in the Constructor, only when necessary

    Hello! I am new to Java. I have a few really simple question. I know this much so far:
    - Hiding is when a variable overrides another within a stronger (more inner) scope.
    - Hiding is not good convention since it may confuse readers of code.
    So I have this example. It's only part of an example, so it will only be the essential parts:
    package example;
    import java.awt.*;
    public class Application {
         * The options component for this Application.
        Component optWindow;
        public Application() {
            Window optWindow = new OptionWindow();
            optWindow.pack();
            this.optWindow = optWindow;
        public void showOptions() {
            optWindow.setVisible(true);
        @Override protected void finalize() throws Throwable {
            optWindow.setVisible(false);
            optWindow = null;
            super.finalize();
    class OptionWindow extends Frame {
        public OptionWindow() {
            super("Options:");
    }Anyway, I also know that optWindow in the constructor hides this.optWindow. But I'm not sure 100% why.
    My reasoning behind wanting to do this is that I don't think that the rest of the Application needs to know that optWindow is a Window other than in the constructor, so the Application Object should store it as just an abstract component. A sort of "type encapsulation and subclass separation".
    I believe that the reason why this is hiding is because optWindow refers to the "reference" of the OptionWindow object, not the object itself =) I understand that so far.
    But I believe it shouldn't because the this.optWindow does not refer to anything until after the constructor, so it shouldn't be hidden.
    I have a few solutions I know of:
    1) Drop the idea of storing optWindow as a Component in the Application Objects. Just store it as a window everywhere.
    2) Keep it this way anyway.
    3) Use a different variable name for the optWindow in the constructor.
    There are in the order that I'd rather do them in. I understand that option 1 is the best. Option 2 might potentially be okay. Option 3, I really do not like since it's giving two names or references to the same object and it would be annoying to come up with a new name for it. But I could come up with something simple like "window" if necessary inside of the constructor.
    My questions would be:
    1) Is this a good idea to make the window an abstract component outside of the constructor?
    2) Is this a "good" use of hiding; or does the rule always apply to avoid hiding?
    If Question 1 is true, I'd probably go with Option 1. If Question 1 is false, but Question 2 is true, I'll go with Option 2. If Question 1 is still false, but so is Question 2, I'll go with Option 3.
    Thank you very much in advanced! I really appreciate the help! =) And I look forward to asking more questions.
    Edit: I wrote that OptionWindow throw Frame instead of "extends Frame".
    Edited by: Macleod789 on Mar 30, 2010 2:24 PM

    Macleod789 wrote:
    Hello! I am new to Java. I have a few really simple question. I know this much so far:
    - Hiding is when a variable overrides another within a stronger (more inner) scope.
    - Hiding is not good convention since it may confuse readers of code.It's common and perfectly acceptable in some situations. Constructors and setters come to mind. If your code is well-written, it won't be at all confusing.
    >
    So I have this example. It's only part of an example, so it will only be the essential parts:
    package example;
    import java.awt.*;
    public class Application {
    * The options component for this Application.
    Component optWindow;
    public Application() {
    Window optWindow = new OptionWindow();
    optWindow.pack();
    this.optWindow = optWindow;
    public void showOptions() {
    optWindow.setVisible(true);
    @Override protected void finalize() throws Throwable {
    optWindow.setVisible(false);
    optWindow = null;
    super.finalize();
    class OptionWindow extends Frame {
    public OptionWindow() {
    super("Options:");
    }Anyway, I also know that optWindow in the constructor hides this.optWindow. But I'm not sure 100% why.Because the JLS defines that it does. Local variables always hide members of the same name. That's the rule the designers decided on.
    My reasoning behind wanting to do this is that I don't think that the rest of the Application needs to know that optWindow is a Window other than in the constructor, so the Application Object should store it as just an abstract component. A sort of "type encapsulation and subclass separation".\Huh? Reason behind doing what? Declaring the optWindow member as a Component rather than a Window? Well, yeah, if the rest of the Application class only cares that it's a Component and could do its job the same way if any other Component were used, then you're right--declaring it as a Component is the correct approach. But then it should not be named optWindow. And if the rest of the Application class doesn't need it to be a Window, then the c'tor has no reason to require that either.
    I believe that the reason why this is hiding is because optWindow refers to the "reference" of the OptionWindow object, not the object itself =) I understand that so far.Reference vs. object is an important distinction to understand. However, it has nothing to do with hiding. Hiding is just about identifier names, like variables. The fact that their values are references is irrelevant to the hiding rules.
    But I believe it shouldn't because the this.optWindow does not refer to anything until after the constructor, so it shouldn't be hidden.Show me the part of the JLS that says that hiding has do with whether the variable in question has been assigned or not.
    In some scopes, two distinct identifiers with the same name can exist. There has to be some rule about which one takes precedence when there's no qualification. It's simpler if it's consistent and it's always the local. If it weren't, then a) it would be inconsistent, which would be confusing, and b) we'd need a new keyword or other mechanism to explicitly indicate that we're talking about the local. Or else we simply wouldn't be able to access the local variable in those contexts, which would be pretty stupid, I'm sure you agree.
    I have a few solutions I know of:Solutions to what? What's the problem you're encountering?
    1) Drop the idea of storing optWindow as a Component in the Application Objects. Just store it as a window everywhere.I addressed that above, and it has nothing to do with hiding.
    2) Keep it this way anyway.So, a "solution" to whatever problem you're having is to do nothing and just keep having the "problem"?
    1) Is this a good idea to make the window an abstract component outside of the constructor?If it's Component in the member variable, it should be in the c'tor too. If the c'tor requires a Window, then it must be because the member has to be a Window.
    2) Is this a "good" use of hiding; or does the rule always apply to avoid hiding?It's very common and acceptable to have parameter names match member names where the parameter is being used to set the member.
    Edited by: jverd on Mar 30, 2010 2:49 PM
    Edited by: jverd on Mar 30, 2010 2:50 PM

  • Errors in code that captures images from webcam

    Here is the code
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture; // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture; // JMF 2.1.1e version
    public class JWebCam extends JFrame
    implements WindowListener, ComponentListener
    protected final static int MIN_WIDTH = 320;
    protected final static int MIN_HEIGHT = 240;
    protected static int shotCounter = 1;
    protected JLabel statusBar = null;
    protected JPanel visualContainer = null;
    protected Component visualComponent = null;
    protected JToolBar toolbar = null;
    protected MyToolBarAction formatButton = null;
    protected MyToolBarAction captureButton = null;
    protected Player player = null;
    protected CaptureDeviceInfo webCamDeviceInfo = null;
    protected MediaLocator ml = null;
    protected Dimension imageSize = null;
    protected FormatControl formatControl = null;
    protected VideoFormat currentFormat = null;
    protected Format[] videoFormats = null;
    protected MyVideoFormat[] myFormatList = null;
    protected boolean initialised = false;
    * Constructor
    public JWebCam ( String frameTitle )
    super ( frameTitle );
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch ( Exception cnfe )
    System.out.println ("Note : Cannot load look and feel settings");
    setSize ( 320, 260 ); // default size...
    addWindowListener ( this );
    addComponentListener ( this );
    getContentPane().setLayout ( new BorderLayout() );
    visualContainer = new JPanel();
    visualContainer.setLayout ( new BorderLayout() );
    getContentPane().add ( visualContainer, BorderLayout.CENTER );
    statusBar = new JLabel ("");
    statusBar.setBorder ( new EtchedBorder() );
    getContentPane().add ( statusBar, BorderLayout.SOUTH );
    * Initialise
    * @returns true if web cam is detected
    public boolean initialise ( )
    throws Exception
    return ( initialise ( autoDetect() ) );
    * Initialise
    * @params _deviceInfo, specific web cam device if not autodetected
    * @returns true if web cam is detected
    public boolean initialise ( CaptureDeviceInfo _deviceInfo )
    throws Exception
    statusBar.setText ( "Initialising...");
    webCamDeviceInfo = _deviceInfo;
    if ( webCamDeviceInfo != null )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    try
    setUpToolBar();
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    ml = webCamDeviceInfo.getLocator();
    if ( ml != null )
    player = Manager.createRealizedPlayer ( ml );
    if ( player != null )
    player.start();
    formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
    videoFormats = webCamDeviceInfo.getFormats();
    visualComponent = player.getVisualComponent();
    if ( visualComponent != null )
    visualContainer.add ( visualComponent, BorderLayout.CENTER );
    myFormatList = new MyVideoFormat[videoFormats.length];
    for ( int i=0; i<videoFormats.length; i++ )
    myFormatList = new MyVideoFormat ( (VideoFormat)videoFormats );
    Format currFormat = formatControl.getFormat();
    if ( currFormat instanceof VideoFormat )
    currentFormat = (VideoFormat)currFormat;
    imageSize = currentFormat.getSize();
    visualContainer.setPreferredSize ( imageSize );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.err.println ("Error : Cannot get current video format");
    invalidate();
    pack();
    return ( true );
    else
    System.err.println ("Error : Could not get visual component");
    return ( false );
    else
    System.err.println ("Error : Cannot create player");
    statusBar.setText ( "Cannot create player" );
    return ( false );
    else
    System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
    statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( IOException ioEx )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( NoPlayerException npex )
    statusBar.setText ("Cannot create player");
    return ( false );
    catch ( CannotRealizeException nre )
    statusBar.setText ( "Cannot realize player");
    return ( false );
    else
    return ( false );
    * Dynamically create menu items
    * @returns the device info object if found, null otherwise
    public void setFormat ( VideoFormat selectedFormat )
    if ( formatControl != null )
    player.stop();
    imageSize = selectedFormat.getSize();
    formatControl.setFormat ( selectedFormat );
    player.start();
    statusBar.setText ( "Format : " + selectedFormat );
    currentFormat = selectedFormat;
    visualContainer.setPreferredSize ( currentFormat.getSize() );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.out.println ("Visual component not an instance of FormatControl");
    statusBar.setText ( "Visual component cannot change format" );
    public VideoFormat getFormat ( )
    return ( currentFormat );
    protected void setUpToolBar ( )
    toolbar = new JToolBar();
    // Note : If you supply the 16 x 16 bitmaps then you can replace
    // the commented line in the MyToolBarAction constructor
    formatButton = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
    captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
    toolbar.add ( formatButton );
    toolbar.add ( captureButton );
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    protected void toolbarHandler ( MyToolBarAction actionBtn )
    if ( actionBtn == formatButton )
    Object selected = JOptionPane.showInputDialog (this,
    "Select Video format",
    "Capture format selection",
    JOptionPane.INFORMATION_MESSAGE,
    null, // Icon icon,
    myFormatList, // videoFormats,
    currentFormat );
    if ( selected != null )
    setFormat ( ((MyVideoFormat)selected).format );
    else if ( actionBtn == captureButton )
    Image photo = grabFrameImage ( );
    if ( photo != null )
    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
    else
    System.err.println ("Error : Could not grab frame");
    * autoDetects the first web camera in the system
    * searches for video for windows ( vfw ) capture devices
    * @returns the device info object if found, null otherwise
    public CaptureDeviceInfo autoDetect ( )
    Vector list = CaptureDeviceManager.getDeviceList ( null );
    CaptureDeviceInfo devInfo = null;
    if ( list != null )
    String name;
    for ( int i=0; i<list.size(); i++ )
    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
    name = devInfo.getName();
    if ( name.startsWith ("vfw:") )
    break;
    if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
    return ( devInfo );
    else
    for ( int i = 0; i < 10; i++ )
    try
    name = VFWCapture.capGetDriverDescriptionName ( i );
    if (name != null && name.length() > 1)
    devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
    if ( devInfo != null )
    return ( devInfo );
    catch ( Exception ioEx )
    // ignore errors detecting device
    statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
    return ( null );
    else
    return ( null );
    * deviceInfo
    * @note outputs text information
    public void deviceInfo ( )
    if ( webCamDeviceInfo != null )
    Format[] formats = webCamDeviceInfo.getFormats();
    if ( ( formats != null ) && ( formats.length > 0 ) )
    for ( int i=0; i<formats.length; i++ )
    Format[] aFormat = formats;
    if ( aFormat[i] instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats.getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) { }
    public void windowClosed ( WindowEvent e ) { }
    public void windowDeactivated ( WindowEvent e ) { }
    public void windowDeiconified ( WindowEvent e ) { }
    public void windowIconified ( WindowEvent e ) { }
    public void windowOpened ( WindowEvent e ) { }
    public void componentHidden(ComponentEvent e) { }
    public void componentMoved(ComponentEvent e) { }
    public void componentShown(ComponentEvent e) { }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat _format )
    format = _format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MySnapshot extends JFrame
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();
    when I run it I get the following errors
    BufferToImage cannot convert buffer
    could not grab frame
    pls help

    Do you expect anyone to read this?
    http://forum.java.sun.com/help.jspa?sec=formatting
    By the way, you have a condition that makes it print those messages. Check why that condiiton isn't rue.

  • Updated : No question, just example web cam capture code

    Hi,
    I posted this example a while back, but it had some cosmetic bugs in it.
    Here's an updated version.
    Quick Start
    1. Install JMF 2.1.1e (performance pack version)
    ( see imports list in source code if you really want to run it using the older version 2.1.1c )
    2. You have to set the JMF_HOME or JMFHOME environment variable. Can't remember which one.
    "Nearly sure" it's JMF_HOME.
    3. Connect your camera
    4. run jmfinit ( may need to do a few times until it detects your camera )
    When it does, you're in business, and you can try to run the code
    5. Run java -cp .;%JMF_HOME%\lib\jmf.jar JWebCam
    known issue
    Under Java 1.5 / 5 - When capturing a frame, and then resizing that snapshots JFrame, the image did not always scale up and display.
    That does work under Java 1.3.1_06 .
    Tested on Win98 2nd edition, Java 1.3.1_06, and Creative Web Cam Pro.
    Legal stuff in plain english : This code is available for use by everyone, personal or commercial, no need to mention me in licenses or anything. It's just a demo I knocked up for myself. So I am under no obligation to support this. Use it at your own risk.... that implies you can't blame or sue me for anything that goes wrong.
    If you like the code, I'd be happy to hear whereabouts you are in the world :-)
    Also note : this is the limits of my JMF experience at present.
    If you've a separate question, post it to a new topic!
    regards,
    Owen ( Dublin, Ireland )
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i<videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                // player.stop();       // not needed and big performance hit
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                // player.start();  // not needed and big performance hit
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i<capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i<formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

    Hi,
    Here's a working version.
    If there are no spaces after the "<" symbol, it thinks it's a HTML tag.
    Putting spaces in, stops this.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i < videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                player.stop();
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                player.start();
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i < list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i < capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i < formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

  • No Question, just example web cam capture code

    Hi,
    Since loads of people ask for an example of capturing pics from a web cam, here's one that captures pics, lets you take snapshots, which it displays in another frame. When you shut down the frame it asks if you want to save it to a JPEG.
    I'm mainly posting this to spite Eka_Kupkova, who only visits this forum to shamelessly advertise a commercial Twain based package in every single posting on this forum which mentions web cams.
    Notes : ( Could be more, read the install docs for JMF )
    1. you must download the "performance" version of jmf to capture video.
    2. I "think" you need to setup the JMF_HOME environment variable
    3. Run the jmfinit program to detect your camera and register it.
    I had to run it a couple of times before it worked.
    4. I had 2 icons for my toolbar, BtnFormat.jpg and BtnCapture.jpg.
    They were just 16 x 16 pixel bitmaps, you can make them up yourself.
    5. I assume you've got the webcam working and the driver installed already.
    Ps. if you find this useful, then reply back with where you are in the world. I'm in Dublin, Ireland.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // Ps. I think JMF 2.1.1c used a different package for this class..
    import com.sun.media.vfw.VFWCapture;
    public class JWebCam extends JFrame
                              implements WindowListener,
                                             ComponentListener
         protected final static int MIN_WIDTH  = 320;
         protected final static int MIN_HEIGHT = 240;
         protected static int shotCounter = 1;
         protected JLabel statusBar = null;
         protected Component visualComponent = null;
         protected JToolBar toolbar = null;
         protected MyToolBarAction formatButton  = null;
         protected MyToolBarAction captureButton = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
          * Constructor
        public JWebCam ( String frameTitle )
             super ( frameTitle );
              try
                  UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
             catch ( Exception cnfe )
                  System.out.println ("Note : Cannot load look and feel settings");
             addWindowListener ( this );
             addComponentListener ( this );
             getContentPane().setLayout ( new BorderLayout() );
             statusBar = new JLabel ("Initialising...");
             statusBar.setBorder ( new EtchedBorder() );
             getContentPane().add ( statusBar, BorderLayout.SOUTH );
             setSize ( 320, 260 ); // default size...
             setVisible ( true );
          * Initialise
          * @returns true if web cam is detected
         public boolean initialise ( )
              throws Exception
              return ( initialise ( autoDetect() ) );
          * Initialise
          * @params _deviceInfo, specific web cam device if not autodetected
          * @returns true if web cam is detected
         public boolean initialise ( CaptureDeviceInfo _deviceInfo )
              throws Exception
              webCamDeviceInfo = _deviceInfo;
             if ( webCamDeviceInfo != null )
                  statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                  try
                        // setUpMenu ( );
                        setUpToolBar();
                        getContentPane().add ( toolbar, BorderLayout.NORTH );
                       ml = webCamDeviceInfo.getLocator();
                       if ( ml != null )
                          player = Manager.createRealizedPlayer ( ml );
                          if ( player != null )
                               formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                                    videoFormats = webCamDeviceInfo.getFormats();
                                    setFormat ( (VideoFormat)videoFormats[0] );
                               // player.start();
                                    visualComponent = player.getVisualComponent();
                                    getContentPane().add ( visualComponent, BorderLayout.CENTER );
                                    invalidate();
                                    pack();
                                    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                myFormatList = new MyVideoFormat[videoFormats.length];
                                for ( int i=0; i<videoFormats.length; i++ )
                                     myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                     else
                          statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( true );
                   catch ( IOException ioEx )
                       statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                        return ( false );
                   catch ( NoPlayerException npex )
                        statusBar.setText ("Cannot create player");
                        return ( false );
                   catch ( CannotRealizeException nre )
                        statusBar.setText ( "Cannot realize player");
                        return ( false );
             else
                  return ( false );
          * Dynamically create menu items
          * @returns the device info object if found, null otherwise
         public void setFormat ( VideoFormat selectedFormat )
              if ( formatControl != null )
                   player.stop();
                   statusBar.setText ( "Format : " + selectedFormat );
                   imageSize = selectedFormat.getSize();
                   formatControl.setFormat ( selectedFormat );
                   currentFormat = selectedFormat;
                   setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                   player.start();
              else
                   System.out.println ("Visual component not an instance of FormatControl");
                   statusBar.setText ( "Visual component cannot change format" );
         protected void setUpToolBar ( )
              toolbar = new JToolBar();
              formatButton  = new MyToolBarAction ( "Format",  "BtnFormat.jpg" );
              captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
              if ( formatButton != null )
                    toolbar.add ( formatButton );
              toolbar.add ( captureButton );
              getContentPane().add ( toolbar, BorderLayout.NORTH );
         protected void toolbarHandler ( MyToolBarAction actionBtn )
              if ( actionBtn == formatButton )
                      // JOptionPane.showConfirmDialog ( this, "Format Dialog" );
                      Object selected = JOptionPane.showInputDialog (this,
                                                                     "Select Video format",
                                                                     "Capture format selection",
                                                                     JOptionPane.INFORMATION_MESSAGE,
                                                                     null,          //     Icon icon,
                                                                     myFormatList, // videoFormats,
                                                                     currentFormat );
                   if ( selected != null )
                        setFormat ( ((MyVideoFormat)selected).format );
              else if ( actionBtn == captureButton )
                   Image photo = grabFrameImage ( );
                   MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
          * autoDetects the first web camera in the system
          * @returns the device info object if found, null otherwise
        public CaptureDeviceInfo autoDetect ( )
              Vector list = CaptureDeviceManager.getDeviceList ( null );
              CaptureDeviceInfo devInfo = null;
              if ( list != null )
                   String name;
                   for ( int i=0; i<list.size(); i++ )
                        devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                        name = devInfo.getName();
                      if ( name.startsWith ("vfw:") )
                            break;
                   if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                       return ( devInfo );
                   else
                      for ( int i = 0; i < 10; i++ )
                           try
                               name = VFWCapture.capGetDriverDescriptionName ( i );
                               if (name != null && name.length() > 1)
                                       devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                                       if ( devInfo != null )
                                            return ( devInfo );
                             catch ( Exception ioEx )
                                  // ignore errors detecting device
                                  statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                       return ( null );
              else
                   return ( null );
          * deviceInfo
          * @note outputs text information
         public void deviceInfo ( )
             if ( webCamDeviceInfo != null )
                  Format[] formats = webCamDeviceInfo.getFormats();
                  if ( ( formats != null ) && ( formats.length > 0 ) )
                  for ( int i=0; i<formats.length; i++ )
                       Format aFormat = formats;
                   if ( aFormat instanceof VideoFormat )
                        Dimension dim = ((VideoFormat)aFormat).getSize();
                        System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
                   else
                        System.out.println ("Format " + i + " : " + formats[i].getEncoding() );
         else
              System.out.println ("Error : No web cam detected");
         * grabs a frame's buffer from the web cam / device
         * @returns A frames buffer
         public Buffer grabFrameBuffer ( )
              if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    Buffer buf = fgc.grabFrame();
    return ( buf );
    else
         return ( null );
         * grabs a frame's buffer, as an image, from the web cam / device
         * @returns A frames buffer as an image
         public Image grabFrameImage ( )
              Buffer buffer = grabFrameBuffer();
              if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    Image image = btoi.createImage ( buffer );
    return ( image );
              else
                   System.out.println ("Error : Buffer grabbed is null");
                   return ( null );
         * Closes and cleans up the player
         public void playerClose ( )
              if ( player != null )
         player.close();
         player.deallocate();
         player = null;
         public void windowClosing ( WindowEvent e )
              playerClose();
              System.exit ( 1 );
         public void componentResized(ComponentEvent e)
              Dimension dim = getSize();
              boolean mustResize = false;
              if ( dim.width < MIN_WIDTH )
              dim.width = MIN_WIDTH;
              mustResize = true;
              if ( dim.height < MIN_HEIGHT )
                   dim.height = MIN_HEIGHT;
                   mustResize = true;
              if ( mustResize )
                   setSize ( dim );
         public void windowActivated ( WindowEvent e )      {       }
         public void windowClosed ( WindowEvent e )      {       }
         public void windowDeactivated ( WindowEvent e )     {     }
         public void windowDeiconified ( WindowEvent e )     {     }
         public void windowIconified ( WindowEvent e )     {     }
         public void windowOpened ( WindowEvent e )          {     }
         public void componentHidden(ComponentEvent e)      {       }
         public void componentMoved(ComponentEvent e)     {     }
         public void componentShown(ComponentEvent e)     {     }
         protected void finalize     ( ) throws Throwable
              playerClose();
              super.finalize();
         class MyToolBarAction extends AbstractAction
              public MyToolBarAction ( String name, String imagefile )
                   super ( name, new ImageIcon ( imagefile ) );
              public void actionPerformed ( ActionEvent event )
                   toolbarHandler ( this );
         class MyVideoFormat
              public VideoFormat format;
              public MyVideoFormat ( VideoFormat _format )
                   format = _format;
              public String toString ( )
                   Dimension dim = format.getSize();
                   return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
         class MySnapshot extends JFrame
              protected Image photo = null;
              protected int shotNumber;
              public MySnapshot ( Image grabbedFrame, Dimension imageSize )
                   super ( );
                   shotNumber = shotCounter++;
                   setTitle ( "Photo" + shotNumber );
                   photo = grabbedFrame;
                   setDefaultCloseOperation ( WindowConstants.DO_NOTHING_ON_CLOSE );
                   int imageHeight = photo.getWidth ( this );
                   int imageWidth = photo.getHeight ( this );
                   setSize ( imageSize.width, imageSize.height );
                   final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
                   final JFrame thisCopy = this;
                   saveDialog.setFile ( "Photo" + shotNumber );
                   addWindowListener ( new WindowAdapter()
                             public void windowClosing ( WindowEvent e )
                                  saveDialog.show();
                                  String filename = saveDialog.getFile();
                                  if ( filename != null )
                                       if ( saveJPEG ( filename ) )
                                            JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
                                            setVisible ( false );
                                            dispose();
                                       else
                                            JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
                                  else
                                       setVisible ( false );
                                       dispose();
                   setVisible ( true );
              public void paint ( Graphics g )
                   g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
              * Saves an image as a JPEG
              * @params the image to save
              * @params the filename to save the image as
         public boolean saveJPEG ( String filename )
              boolean saved = false;
         BufferedImage bi = new BufferedImage ( photo.getWidth(null),
         photo.getHeight(null),
         BufferedImage.TYPE_INT_RGB );
         Graphics2D g2 = bi.createGraphics();
         g2.drawImage ( photo, null, null );
         FileOutputStream out = null;
         try
         out = new FileOutputStream ( filename );
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
              JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
              param.setQuality ( 1.0f, false );
              encoder.setJPEGEncodeParam ( param );
              encoder.encode ( bi );
              out.close();
              saved = true;
         catch ( Exception ex )
         System.out.println ("Error saving JPEG : " + ex.getMessage() );
         return ( saved );
         }     // of MySnapshot
    public static void main (String[] args )
         try
              JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
              if ( myWebCam.initialise() )
                   // myWebCam.deviceInfo(); // outputs device info
              else
                   System.out.println ("Web Cam not detected / initialised");
         catch ( Exception ex )
              ex.printStackTrace();

    Doohhh... I posted an old version which didn't work.
    I tried and tested this last night, and it runs grand using Ver 2.1.1e.
    Tested under Windows 98, using an old Creative GO Camera.
    Haven't tried it under Linux, but suspect you'd have to at least change an references to "vfw" to "v4l".
    You'll need jmf.jar in your classpath to run it too.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 320;
        protected final static int MIN_HEIGHT = 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("");
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            return ( initialise ( autoDetect() ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                myFormatList = new MyVideoFormat[videoFormats.length];
                                for ( int i=0; i<videoFormats.length; i++ )
                                    myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                                Format currFormat = formatControl.getFormat();
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                player.stop();
                imageSize = selectedFormat.getSize();
                formatControl.setFormat ( selectedFormat );
                player.start();
                statusBar.setText ( "Format : " + selectedFormat );
                currentFormat = selectedFormat;
                visualContainer.setPreferredSize ( currentFormat.getSize() );
                setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public CaptureDeviceInfo autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            if ( list != null )
                String name;
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        break;
                if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                    return ( devInfo );
                else
                    for ( int i = 0; i < 10; i++ )
                        try
                            name = VFWCapture.capGetDriverDescriptionName ( i );
                            if (name != null && name.length() > 1)
                                devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                                if ( devInfo != null )
                                    return ( devInfo );
                        catch ( Exception ioEx )
                            // ignore errors detecting device
                            statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                    return ( null );
            else
                return ( null );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i<formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame(); );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat _format )
    format = _format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MySnapshot extends JFrame
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

  • Strange Output of Thread

    Hi Friends
    I am getting very strange out put of the following code
    Plz explain!!!!!!!
    class BasicBlob {                                     // (1)
        static    int idCounter;
        static    int population;
        protected int blobId;
        BasicBlob() {
            blobId = idCounter++;
            ++population;
        protected void finalize() throws Throwable {      // (2)
            --population;
            super.finalize();
    class Blob extends BasicBlob {                        // (3)
        int[] fat;
        Blob(int bloatedness) {                           // (4)
            fat = new int[bloatedness];
            System.out.println(blobId + ": Hello");
        protected void finalize() throws Throwable {      // (5)
            System.out.println(blobId + ": Bye");
            super.finalize();
    public class Finalizers {
       public static void main(String[] args) {          // (6)
            int blobsRequired, blobSize;
            try {
                blobsRequired = Integer.parseInt(args[0]);
                blobSize      = Integer.parseInt(args[1]);
            } catch(IndexOutOfBoundsException e) {
                System.err.println(
                    "Usage: Finalizers <number of blobs> <blob size>");
                return;
            for (int i=0; i<=blobsRequired; ++i) {         // (7)
                new Blob(blobSize);
            System.out.println(BasicBlob.population + " blobs alive"); // (8)
       When I give the i/p 5 500000
    O/P is--------------------------
    0: Hello
    0: Bye
    1: Hello
    1: Bye
    2: Hello
    2: Bye
    3: Hello
    3: Bye
    4: Hello ////////// Why not Bye again as above 1 blobs alive
    1 blobs alive

    This has to do with whether Garbage Collector is collecting your unreferenced objects or not. In this case you are specifying a size of 500000, which from ur code is size of an array of integers (each 4 byte). so a single allocation of array corresponds to roughly 500000*4 bytes. On this size jvm heap will run out of memory for even 2 such objects and hence when it goes to create second object GC runs and your previous object is GC'ed. But for last object created this is not the case.
    U can try changing 500000 with a lesser value, say 500. All of your blobs will remain alive (if unfortunately they are not gc'ed :)).

  • Clearing Images and Destroying Instances

    Two separate questions here.
    First I'd like to know how to clear an image that has been drawn, with it being on a random background with multiple colors, without having to redraw the background over and over again. I have an image that moves across the screen and I have the background update only when it needs to to save processing power, but now, obviously, the moving image remains drawn wherever it goes. That or if there's a way to "move" an already drawn image.
    Secondly, I'd like to know how to delete an instance of a class from within that class. I have a class that gets called a lot (example: Caller.java), and each time it's called, it creates a new instance of another class (example: NewClass.java), but when Caller.java is called, it is only used once, and I don't want all those instances to just remain there. I'd like to force GC to take care of them at the end of their tasks.
    If anyone can provide answers to either of those questions, thank you.

    hi,
    try to read this it may helpfor the subject:its from thinking in java 2nd edition by bruce eckel:
    Cleanup: finalization and
    garbage collection
    Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply �letting go� of an object once you�re done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very unusual case. Suppose your object allocates �special� memory without using new. The garbage collector knows only how to release memory allocated with new, so it won�t know how to release the object�s �special� memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here�s how it�s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object�s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection. [ Add Comment ]
    This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way: [ Add Comment ]
    Garbage collection is not destruction.
    If you remember this, you will stay out of trouble. What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose in the process of creating your object it draws itself on the screen. If you don�t explicitly erase its image from the screen, it might never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage-collected, the image will first be removed from the screen, but if it isn�t, the image will remain. So a second point to remember is: [ Add Comment ]
    Your objects might not get garbage-collected.
    You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense. [ Add Comment ]
    What is finalize( ) for?
    You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it? [ Add Comment ]
    A third point to remember is:
    Garbage collection is only about memory.
    That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. [ Add Comment ]
    Does this mean that if your object contains other objects finalize( ) should explicitly release those objects? Well, no�the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases, in which your object can allocate some storage in some way other than creating an object. But, you might observe, everything in Java is an object so how can this be? [ Add Comment ]
    It would seem that finalize( ) is in place because of the possibility that you�ll do something C-like by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. (Native methods are discussed in Appendix B.) C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C�s malloc( ) family of functions might be called to allocate storage, and unless you call free( ) that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you�d need to call it in a native method inside your finalize( ). [ Add Comment ]
    After reading this, you probably get the idea that you won�t use finalize( ) much. You�re correct; it is not the appropriate place for normal cleanup to occur. So where should normal cleanup be performed? [ Add Comment ]
    You must perform cleanup
    To clean up an object, the user of that object must call a cleanup method at the point the cleanup is desired. This sounds pretty straightforward, but it collides a bit with the C++ concept of the destructor. In C++, all objects are destroyed. Or rather, all objects should be destroyed. If the C++ object is created as a local (i.e., on the stack�not possible in Java), then the destruction happens at the closing curly brace of the scope in which the object was created. If the object was created using new (like in Java) the destructor is called when the programmer calls the C++ operator delete (which doesn�t exist in Java). If the C++ programmer forgets to call delete, the destructor is never called and you have a memory leak, plus the other parts of the object never get cleaned up. This kind of bug can be very difficult to track down. [ Add Comment ]
    In contrast, Java doesn�t allow you to create local objects�you must always use new. But in Java, there�s no �delete� to call to release the object since the garbage collector releases the storage for you. So from a simplistic standpoint you could say that because of garbage collection, Java has no destructor. You�ll see as this book progresses, however, that the presence of a garbage collector does not remove the need for or utility of destructors. (And you should never call finalize( ) directly, so that�s not an appropriate avenue for a solution.) If you want some kind of cleanup performed other than storage release you must still explicitly call an appropriate method in Java, which is the equivalent of a C++ destructor without the convenience. [ Add Comment ]
    One of the things finalize( ) can be useful for is observing the process of garbage collection. The following example shows you what�s going on and summarizes the previous descriptions of garbage collection:
    //: c04:Garbage.java
    // Demonstration of the garbage
    // collector and finalization
    class Chair {
    static boolean gcrun = false;
    static boolean f = false;
    static int created = 0;
    static int finalized = 0;
    int i;
    Chair() {
    i = ++created;
    if(created == 47)
    System.out.println("Created 47");
    public void finalize() {
    if(!gcrun) {
    // The first time finalize() is called:
    gcrun = true;
    System.out.println(
    "Beginning to finalize after " +
    created + " Chairs have been created");
    if(i == 47) {
    System.out.println(
    "Finalizing Chair #47, " +
    "Setting flag to stop Chair creation");
    f = true;
    finalized++;
    if(finalized >= created)
    System.out.println(
    "All " + finalized + " finalized");
    public class Garbage {
    public static void main(String[] args) {
    // As long as the flag hasn't been set,
    // make Chairs and Strings:
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    System.out.println(
    "After all Chairs have been created:\n" +
    "total created = " + Chair.created +
    ", total finalized = " + Chair.finalized);
    // Optional arguments force garbage
    // collection & finalization:
    if(args.length > 0) {
    if(args[0].equals("gc") ||
    args[0].equals("all")) {
    System.out.println("gc():");
    System.gc();
    if(args[0].equals("finalize") ||
    args[0].equals("all")) {
    System.out.println("runFinalization():");
    System.runFinalization();
    System.out.println("bye!");
    } ///:~
    The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs. Since the garbage collector can run at any time, you don�t know exactly when it will start up, so there�s a flag called gcrun to indicate whether the garbage collector has started running yet. A second flag f is a way for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are set within finalize( ), which is called during garbage collection. [ Add Comment ]
    Two other static variables, created and finalized, keep track of the number of Chairs created versus the number that get finalized by the garbage collector. Finally, each Chair has its own (non-static) int i so it can keep track of what number it is. When Chair number 47 is finalized, the flag is set to true to bring the process of Chair creation to a stop. [ Add Comment ]
    All this happens in main( ), in the loop
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    You might wonder how this loop could ever finish, since there�s nothing inside the loop that changes the value of Chair.f. However, the finalize( ) process will, eventually, when it finalizes number 47. [ Add Comment ]
    The creation of a String object during each iteration is simply extra storage being allocated to encourage the garbage collector to kick in, which it will do when it starts to get nervous about the amount of memory available. [ Add Comment ]
    When you run the program, you provide a command-line argument of �gc,� �finalize,� or �all.� The �gc� argument will call the System.gc( ) method (to force execution of the garbage collector). Using the �finalize� argument calls System.runFinalization( ) which�in theory�will cause any unfinalized objects to be finalized. And �all� causes both methods to be called. [ Add Comment ]
    The behavior of this program and the version in the first edition of this book shows that the whole issue of garbage collection and finalization has been evolving, with much of the evolution happening behind closed doors. In fact, by the time you read this, the behavior of the program may have changed once again. [ Add Comment ]
    If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily the case with previous implementations of the JDK, although the documentation claimed otherwise. In addition, you�ll see that it doesn�t seem to make any difference whether System.runFinalization( ) is called. [ Add Comment ]
    However, you will see that only if System.gc( ) is called after all the objects are created and discarded will all the finalizers be called. If you do not call System.gc( ), then only some of the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was introduced that caused programs to run all the finalizers as they exited, but the design turned out to be buggy and the method was deprecated. This is yet another clue that the Java designers were thrashing about trying to solve the garbage collection and finalization problem. We can only hope that things have been worked out in Java 2. [ Add Comment ]
    The preceding program shows that the promise that finalizers will always be run holds true, but only if you explicitly force it to happen yourself. If you don�t cause System.gc( ) to be called, you�ll get an output like this:
    Created 47
    Beginning to finalize after 3486 Chairs have been created
    Finalizing Chair #47, Setting flag to stop Chair creation
    After all Chairs have been created:
    total created = 3881, total finalized = 2684
    bye!
    Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called, it will finalize and destroy all the objects that are no longer in use up to that point. [ Add Comment ]
    Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual Machine (JVM) isn�t close to running out of memory, then it will (wisely) not waste time recovering memory through garbage collection. [ Add Comment ]
    The death condition
    In general, you can�t rely on finalize( ) being called, and you must create separate �cleanup� functions and call them explicitly. So it appears that finalize( ) is only useful for obscure memory cleanup that most programmers will never use. However, there is a very interesting use of finalize( ) which does not rely on it being called every time. This is the verification of the death condition[29] of an object. [ Add Comment ]
    At the point that you�re no longer interested in an object�when it�s ready to be cleaned up�that object should be in a state whereby its memory can be safely released. For example, if the object represents an open file, that file should be closed by the programmer before the object is garbage-collected. If any portions of the object are not properly cleaned up, then you have a bug in your program that could be very difficult to find. The value of finalize( ) is that it can be used to discover this condition, even if it isn�t always called. If one of the finalizations happens to reveal the bug, then you discover the problem, which is all you really care about. [ Add Comment ]
    Here�s a simple example of how you might use it:
    //: c04:DeathCondition.java
    // Using finalize() to detect an object that
    // hasn't been properly cleaned up.
    class Book {
    boolean checkedOut = false;
    Book(boolean checkOut) {
    checkedOut = checkOut;
    void checkIn() {
    checkedOut = false;
    public void finalize() {
    if(checkedOut)
    System.out.println("Error: checked out");
    public class DeathCondition {
    public static void main(String[] args) {
    Book novel = new Book(true);
    // Proper cleanup:
    novel.checkIn();
    // Drop the reference, forget to clean up:
    new Book(true);
    // Force garbage collection & finalization:
    System.gc();
    } ///:~
    The death condition is that all Book objects are supposed to be checked in before they are garbage-collected, but in main( ) a programmer error doesn�t check in one of the books. Without finalize( ) to verify the death condition, this could be a difficult bug to find. [ Add Comment ]
    Note that System.gc( ) is used to force finalization (and you should do this during program development to speed debugging). But even if it isn�t, it�s highly probable that the errant Book will eventually be discovered through repeated executions of the program (assuming the program allocates enough storage to cause the garbage collector to execute). [ Add Comment ]

  • Use of dispose() and finalize()

    Hello everyone (first post ever). I have a question about a program that I'm currently working on that doesn't seem to be releasing system resources. Here's a brief description of my program and my problem:
    Program Description: It's a widget that queries a news file every couple of minutes to check if the file was updated. If it was updated, then the taskbar icon flashes and signals the user to click on it to open a window showing them the news.
    Problem: The main use of this program will be just sitting in the taskbar waiting and checking to see if there are any updates. However, after a user opens the window, the memory usage obviously spikes to show the content of the window. After the window is closed, the memory stays allocated and never seems to go back down to it's memory usage when it was just sitting in the taskbar. I have the window set to dispose on close and have fiddled around with adding finalize() and dispose() statements in a couple of different places. I also don't call anything from this class in any of my other classes.
    Here is my Window.class, where I'm hoping the problem is. Thanks.
    package mainFiles;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    // The part of the program that displays the main window of the widget
    public class Window extends JFrame implements ActionListener, WindowListener {
         private static final long serialVersionUID = 1L;
         // Declare the global variables used in the method
         private JButton updateButton;
         // The default constructor of the window
         public Window() {
              // Create the container for holding the content of the widget
              JFrame mainWindow = new JFrame();
              mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              this.centerWindow(mainWindow, 475, 350);
              mainWindow.addWindowListener(this);
              // Customize the look of the JFrame a little bit
              mainWindow.setIconImage(new ImageIcon("system/images/tray_inactive.gif").getImage());
              mainWindow.setTitle("Widget Text");
              mainWindow.setResizable(false);
              // Create the home panel of the widget
              WindowBackground homePanel = new WindowBackground();
              mainWindow.setContentPane(homePanel);
              homePanel.setLayout(new BoxLayout(homePanel, BoxLayout.X_AXIS));
              // Create the left side of the window
              JPanel leftPanel = new JPanel();
              leftPanel.setOpaque(false);
              leftPanel.setPreferredSize(new Dimension(104,324));
              homePanel.add(leftPanel);
              // Add a spacer to the left panel from the top
              leftPanel.add(Box.createRigidArea(new Dimension(104,16)));
              // Add the update button to the left side of the widget
              updateButton = new JButton("Refresh");
              updateButton.addActionListener(this);
              leftPanel.add(updateButton);
              // Create the right side of the window
              JPanel rightPanel = new JPanel();
              rightPanel.setOpaque(false);
              rightPanel.setPreferredSize(new Dimension(365,324));
              homePanel.add(rightPanel);
              // Add a spacer to the right panel from the top
              rightPanel.add(Box.createRigidArea(new Dimension(365,16)));
              // Create the scrollpane which allows the news to be scrolled up and down
              JScrollPane contentScrollPane = new JScrollPane(Content.mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              contentScrollPane.getViewport().setOpaque(false);
              contentScrollPane.setOpaque(false);
              contentScrollPane.setEnabled(true);
              // Set the size of the scrollpane, then add it to the right panel
              contentScrollPane.setPreferredSize(new Dimension(356,290));
              rightPanel.add(contentScrollPane);
              // Create an empty border around the scrollpane to remove the border
              Border empty = new EmptyBorder(0,0,0,0);
              contentScrollPane.setBorder(empty);
              contentScrollPane.setViewportBorder(empty);
              // Whenever the window is opened, update the tray icon to inactive
              Widget.updateIconToInactive();
              // Show the window to the user
              mainWindow.setVisible(true);
         // If the main window of the widget is closed, then give the user the ability to make a new one
         public void windowClosing(WindowEvent event) {
              // Set the window to no longer being active
              Widget.windowActive = false;
              // *** This doesn't seem to work
              this.removeAll();
              System.gc();
         // For centering the window on the user's desktop
         public void centerWindow(JFrame window, int width, int height) {
              // Set the size of the window to the size wanted
              window.setSize(width, height);
              // Get the two sizes and compute the average size between them
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              Dimension windowSize = window.getSize();
              int x = (screenSize.width / 2) - (windowSize.width / 2);
              int y = (screenSize.height / 2) - (windowSize.height / 2);
              // Set the location to the center of the screen
              window.setLocation(x, y);
         // Whenever a new WindowBackground is created, paint the background image on it
         public class WindowBackground extends JPanel {
              private static final long serialVersionUID = 1L;
              // Paint the background on the panel
              public void paintComponent(Graphics g) {
                   ImageIcon background = new ImageIcon("system/images/bg_window.gif");
                   background.paintIcon(this, g, 0, 0);
         // For responding to actions performed in the interface
         public void actionPerformed(ActionEvent event) {
              // If the user pushes the manual update button, then check for new updates
              if (event.getSource() == updateButton)
                   Content.check();
         // Although these aren't used, they must be included in the class
         public void windowActivated(WindowEvent arg0) {}
         public void windowClosed(WindowEvent arg0) {}
         public void windowDeactivated(WindowEvent arg0) {}
         public void windowDeiconified(WindowEvent arg0) {}
         public void windowIconified(WindowEvent arg0) {}
         public void windowOpened(WindowEvent arg0) {}
    }

    I'll try to describe it in some more detail:
    When the program first starts up, memory usage is around 9K to 11K, since the only task it has is to check an external file every five minutes to see if it's been updated. If there is an update, then the icon blinks which alerts the user that there is an update available. When they click on the icon, a window pops up displaying the news. Memory usage at this points run up to about 25K. Now this is where the problem comes in. After the window is closed, it should be disposed. Now, from what I understand, that means that the Garbage Collector should destroy it at some point and release the memory that's being used. However, many hours after the window has been closed, the memory usage is still at 25K. I just don't understand why it isn't using 9K-11K at that point.
    The main reason I care so much about memory usage is because this is a program that is going to be running in the background while users play PC games. It's mainly to get in touch with each other and tell each other when an event is happening in a specific game.

  • Keep getting VncViewer.class not found error when trying to use Windows 7

    Greetings,
    I have no issue accessing the OVM Manager 2.2 with OEL 5.4 x86_64 with the latest Java release from ULN. But when I use a Windows 7 client ( x86) with the Sun Java 6 Update 18 I get the following error when trying to access the Console of a VM Guest:
    Java Plug-in 1.6.0_18
    Using JRE version 1.6.0_18-b07 Java HotSpot(TM) Client VM
    User home directory = C:\Users\deverej
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    load: class VncViewer.class not found.
    java.lang.ClassNotFoundException: VncViewer.class
         at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed:http://141.144.112.202:8888/OVS/faces/app/VncViewer/class.class
         at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 7 more
    Exception: java.lang.ClassNotFoundException: VncViewer.class
    I am curious fi I should use only a specifc Java Engine with IE 7 or the latest Firefox browers.

    Same issue to with Windows XP SP3 x86 with Java Runtime Enviornment 1.5.0_15
    J2SE Enviornment 5.0 Update 15
    Java 6 Update 17

  • I need a solution of this complicated problem to finalize my final project

    Introduction
    This project revolves around an important text processing task, text compression. In particular, you will be required to encode a sequence of words read from a source file into binary strings (using only the characters 0 and 1). It is important to note that text compression makes it possible to minimize the time needed to transmit text over a low-bandwidth channel, such as infrared connection. Moreover, text compression is helpful in storing large documents more efficiently. The coding scheme explored in this project is the Huffman Coding Scheme. While standard encoding schemes, such as Unicode and ASCII, use fixed-length binary strings to encode characters, Huffman coding assigns variable-length codes to characters. The length of a Huffman code depends on the relative frequency of its associated character. Specifically, Huffman coding capitalizes on the fact that some characters are used more frequently than others to use short codewords when encoding high-frequency characters and long codewords to encode low-frequency characters. Huffman coding saves space over state of the art fixed-length encoding and is therefore at the heart of file compression techniques in common use today. Figure 1 shows the relative frequencies of the letters of the alphabet as they appear in a representative sample of English documents.
    Letter     Frequency     Letter     Frequency
    A     77     N     67
    B     17     O     67
    C     32     P     20
    D     42     Q     5
    E     120     R     59
    F     24     S     67
    G     17     T     85
    H     50     U     37
    I     76     V     12
    J     4     W     22
    K     7     X     4
    L     42     Y     22
    M     24     Z     2
    Figure 1. Relative frequencies for the 26 letters of the alphabet.
    Huffman coding and decoding
    Huffman’s algorithm for producing optimal variable-length codes is based on the construction of a binary tree T that represents the code. In other words, the Huffman code for each character is derived from a full binary tree known as the Huffman coding tree, or simply the Huffman tree. Each edge in the Huffman tree represents a bit in a codeword, with each edge connecting a node with its left child representing a “0” and each edge connecting a node with its right child representing a “1”. Each external node in the tree is associated with a specific character, and the Huffman code for a character is defined by the sequence of bits in the path from the root to the leaf corresponding to that character. Given codes for the characters, it is a simple matter to use these codes to encode a text message. You will have simply to replace each letter in the string with its binary code (a lookup table can be used for this purpose).
    In this project, you are not going to use the table given in Figure 1 to determine the frequency of occurrence per character. Instead, you will derive the frequency corresponding to a character by counting the number of times that character appears in an input file. For example, if the input file contains the following line of text “a fast runner need never be afraid of the dark”, then the frequencies listed in the table given in Figure 2 should be used per character:
    Character          a     b     d     e     f     H     i     k     n     O     r     s     t     u     v
    Frequency     9     5     1     3     7     3     1     1     1     4     1     5     1     2     1     1
    Figure 2. The frequency of each character of the String X.
    Based on the frequencies shown in Figure 2, the Huffman tree depicted in Figure 3 can be constructed:
    Figure 3. Huffman tree for String X.
    The code for a character is thus obtained by tracing the path from the root of the Huffman tree to the external node where that character is stored, and associating a left edge with 0 and a right edge with 1. In the context of the considered example for instance, the code for “a” is 010, and the code for “f” is 1100.
    Once the Huffman tree is constructed and the message obtained from the input file has been encoded, decoding the message is done by looking at the bits in the coded string from left to right until all characters are decoded. This can be done by using the Huffman tree in a reverse process from that used to generate the codes. Decoding the bit string begins at the root of the tree. Branches are taken depending on the bit value – left for ‘0’ and right for ‘1’ – until reaching a leaf node. This leaf contains the first character in the message. The next bit in the code is then processed from the root again to start the next character. The process is repeated until all the remaining characters are decoded. For example, to decode the string “0101100” in the case of the example under study, you begin at the root of the tree and take a left branch for the first bit which is ‘0’. Since the next bit is a ‘1’, you take a right branch. Then, you take a left branch (for the third bit ‘1’), arriving at the leaf node corresponding to the letter a. Thus, the first letter of the coded word is a. You then begin again at the root of the tree to process the fourth bit, which is a ‘1’. Taking 2 right branches then two left branches, you reach the leaf node corresponding to the letter f.
    Problem statement
    You are required to implement the Huffman coding/decoding algorithms. After you complete the implementation of the coding/decoding processes, you are asked to use the resulting Java code to:
    1.     Read through a source file called “in1.dat” that contains the following paragraph:
    “the Huffman coding algorithm views each of the d distinct characters of the string X as being in separate Huffman trees initially with each tree composed of a single leaf node these separate trees will eventually be joined into a single Huffman tree in each round the algorithm takes the two binary trees with the smallest frequencies and merges them into a single binary tree it repeats this process until only one tree is left.”
    2.     Determine the actual frequencies for all the letters in the file.
    3.     Use the frequencies from the previous step to create a Huffman coding tree before you assign codes to individual letters. Use the LinkedBinaryTree class that we developed in class to realize your Huffman coding trees.
    4.     Produce an encoded version of the input file “in1.dat” and then store it in an output file called “out.dat”.
    5.     Finally, the decoding algorithm will come into play to decipher the codes contained in “out.dat”. The resulting decoded message should be written to an output file called “in2.dat”. If nothing goes wrong, the text stored in “in1.dat” and the one in “in2.dat” must match up correctly.

    jschell wrote:
    I need a solution of this complicated problem to finalize my final project The solution:
    1. Write code
    2. Test code3. If test fails, debug code, then go to step 2.

  • JVM crash when adding method to class

    Hello,
    I am getting some kind of problem with the virtual machine. The JVM crashes when making a class (with new). It happened when I was adding some functionality to the class, I worked my way backwards and discovered it crashes when I add any new methods, if I comment them out again everything works, adding a method by any name causes to crash.
    I went in debug to find out where it was happening, and it happens on this line:
    public PerspectiveActionToolBarHeader createPerspectiveActionToolBarHeader() {
         PerspectiveActionToolBarHeader ret = null;
         ret = new PerspectiveActionToolBarHeader(this); // << here
         return ret;
    }The PerspectiveActionToolBarHeader is the class where adding methods causes it to fail. For example, it has the method
    public Container getContainer() {
         return this;
    }and works, but if I add:
    public void anything(){} it causes a crash on the new PerspectiveActionToolBarHeader(this);
    When stepped into with the debugger it goes to the (source not found) ClassNotFoundException and eventually before the crash the (stack?) looks like this:
    Launcher$AppClassLoader(ClassLoader).loadClass(String) line: not available     
    MaldiSoftwareOptionsUIEnsemble(PerspectiveUIEnsemble).createPerspectiveActionToolBarHeader() line: 72
    and the debugger describes the class just before the crash:
    Launcher$AppClassLoader (id=44)     
    arg0     "saiman.uiobjnew.PerspectiveToolBarButton" (id=51) << has just changed
    and the log file (not sure how much to copy here!):
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_ILLEGAL_INSTRUCTION (0xc000001d) at pc=0x005c0001, pid=15504, tid=20112
    # JRE version: 6.0_24-b07
    # Java VM: Java HotSpot(TM) Client VM (19.1-b02 mixed mode windows-x86 )
    # Problematic frame:
    # C 0x005c0001
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    --------------- T H R E A D ---------------
    Current thread (0x011ca000): JavaThread "main" [_thread_in_vm, id=20112, stack(0x01140000,0x01190000)]
    siginfo: ExceptionCode=0xc000001d
    Registers:
    EAX=0x13e13248, EBX=0x6da0daa8, ECX=0x13e13250, EDX=0x13e131f8
    ESP=0x0118f93c, EBP=0x0118f9a0, ESI=0x011ca9b0, EDI=0x011ca9ac
    EIP=0x005c0001, EFLAGS=0x00010206
    Register to memory mapping:
    EAX=0x13e13248
    {method}
    - klass: {other class}
    EBX=0x6da0daa8
    0x6da0daa8 is pointing to unknown location
    ECX=0x13e13250
    {method}
    - klass: {other class}
    EDX=0x13e131f8
    {constMethod}
    - klass: {other class}
    - method: 0x13e13248 {method} 'flipVisible' '(I)V' in 'saiman/uiobjnew/PerspectiveActionToolBarHeader'
    - exceptions: 0x13bf11e8
    ESP=0x0118f93c
    0x0118f93c is pointing into the stack for thread: 0x011ca000
    "main" prio=6 tid=0x011ca000 nid=0x4e90 runnable [0x0118f000]
    java.lang.Thread.State: RUNNABLE
    EBP=0x0118f9a0
    0x0118f9a0 is pointing into the stack for thread: 0x011ca000
    "main" prio=6 tid=0x011ca000 nid=0x4e90 runnable [0x0118f000]
    java.lang.Thread.State: RUNNABLE
    ESI=0x011ca9b0
    0x011ca9b0 is pointing to unknown location
    EDI=0x011ca9ac
    0x011ca9ac is pointing to unknown location
    Top of Stack: (sp=0x0118f93c)
    0x0118f93c: 6d94272d 011ca370 13e17d40 011ca000
    0x0118f94c: 011ca000 01a30950 011ca748 011ca9b4
    0x0118f95c: 011cab3c 0118fb28 011c6748 011ca348
    0x0118f96c: 011ca370 011ca73c 6da0daa8 011ca350
    0x0118f97c: 011ca370 0118f9cc 011ca9a8 0118f9c8
    0x0118f98c: 011ca788 011ca370 011ca9b0 011ca000
    0x0118f99c: 13e17d40 0118f9cc 6d943009 00000910
    0x0118f9ac: 011ca9ac 00000001 011ca000 011ca000
    Instructions: (pc=0x005c0001)
    0x005bfff1: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ff
    0x005c0001: ff ff 7f 00 00 00 00 00 00 00 00 ff ff ff ff 00
    Stack: [0x01140000,0x01190000], sp=0x0118f93c, free space=318k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    C 0x005c0001
    V [jvm.dll+0x153009]
    V [jvm.dll+0xdecdb]
    V [jvm.dll+0xe1887]
    V [jvm.dll+0xe1c46]
    V [jvm.dll+0xec09a]
    j saiman.uiobjnew.PerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+2
    j saiman.mv.ModelViewPerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.addButtons()V+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+21
    j saiman.mv.ModelViewPerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.uiobjnew.SoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.wmaldi.MaldiSoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.newuiimpl.MassSpectrumMainFrameImpl.main([Ljava/lang/String;)V+173
    v ~StubRoutines::call_stub
    V [jvm.dll+0xf0ab9]
    V [jvm.dll+0x1837d1]
    V [jvm.dll+0xf0b3d]
    V [jvm.dll+0xfa0d6]
    V [jvm.dll+0x101cde]
    C [javaw.exe+0x2155]
    C [javaw.exe+0x8614]
    C [kernel32.dll+0x51194]
    C [ntdll.dll+0x5b3f5]
    C [ntdll.dll+0x5b3c8]
    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j saiman.uiobjnew.PerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+2
    j saiman.mv.ModelViewPerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.addButtons()V+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+21
    j saiman.mv.ModelViewPerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.uiobjnew.SoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.wmaldi.MaldiSoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.newuiimpl.MassSpectrumMainFrameImpl.main([Ljava/lang/String;)V+173
    v ~StubRoutines::call_stub
    --------------- P R O C E S S ---------------
    Java Threads: ( => current thread )
    0x01b05400 JavaThread "AWT-Windows" daemon [_thread_in_native, id=19680, stack(0x18560000,0x185b0000)]
    0x01b04800 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=19516, stack(0x18140000,0x18190000)]
    0x01b04000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=20064, stack(0x18040000,0x18090000)]
    0x01b03c00 JavaThread "CompilerThread0" daemon [_thread_blocked, id=20276, stack(0x17ff0000,0x18040000)]
    0x01aeb000 JavaThread "JDWP Command Reader" daemon [_thread_in_native, id=16832, stack(0x17fa0000,0x17ff0000)]
    0x01aea000 JavaThread "JDWP Event Helper Thread" daemon [_thread_blocked, id=16360, stack(0x17ef0000,0x17f40000)]
    0x01ae8000 JavaThread "JDWP Transport Listener: dt_socket" daemon [_thread_blocked, id=20084, stack(0x17ea0000,0x17ef0000)]
    0x01ade400 JavaThread "Attach Listener" daemon [_thread_blocked, id=19772, stack(0x17d90000,0x17de0000)]
    0x01add400 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=20192, stack(0x17d40000,0x17d90000)]
    0x01ab2800 JavaThread "Finalizer" daemon [_thread_blocked, id=17344, stack(0x17cf0000,0x17d40000)]
    0x01aabc00 JavaThread "Reference Handler" daemon [_thread_blocked, id=19964, stack(0x17ca0000,0x17cf0000)]
    =>0x011ca000 JavaThread "main" [_thread_in_vm, id=20112, stack(0x01140000,0x01190000)]
    Other Threads:
    0x01aa7c00 VMThread [stack: 0x011d0000,0x01220000] [id=19144]
    0x01b17400 WatcherThread [stack: 0x180f0000,0x18140000] [id=12792]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 4928K, used 768K [0x03bf0000, 0x04140000, 0x09140000)
    eden space 4416K, 5% used [0x03bf0000, 0x03c30380, 0x04040000)
    from space 512K, 100% used [0x040c0000, 0x04140000, 0x04140000)
    to space 512K, 0% used [0x04040000, 0x04040000, 0x040c0000)
    tenured generation total 10944K, used 1858K [0x09140000, 0x09bf0000, 0x13bf0000)
    the space 10944K, 16% used [0x09140000, 0x09310948, 0x09310a00, 0x09bf0000)
    compacting perm gen total 12288K, used 9598K [0x13bf0000, 0x147f0000, 0x17bf0000)
    the space 12288K, 78% used [0x13bf0000, 0x1454fb70, 0x1454fc00, 0x147f0000)
    No shared spaces configured.
    Edited by: hanvyj on 07-Jun-2011 02:39
    Edited by: hanvyj on 07-Jun-2011 02:43

    I think I may have stumbled across the answer, It seems that the abstract class PerspectiveToolBar implements
    the interface with the method public Container getContainer() but does not declare it, this should be fine because the method is abstract but it crashes. When I add the method public abstract Container getContainer(); to the abstract sub-class there is no error. I'm going to try make a small compilable example to see if I can reproduce it.
    edit its actually only one of the two interface methods, and not getContainer(), but another one. If anyone is interested here is the interface:
    public interface IMassSpectrometerPassableControlContainer
         Container getContainer();
         void reloadWidgetsOnVisible(boolean visible);
    }and it works only if there is "public abstract void reloadWidgetsOnVisible(boolean visible);" in the abstract class PerspectiveToolBar implementing IMassSpectrometerPassableControlContainer.
    I tried to reproduce it, but I can't get another class to repeat the behaviour, so I don't think I can post a bug report on it. Here is my attempt anyway:
    import javax.swing.JToolBar;
    * Class     Test.java
    * Date:     7 Jun 2011
    * @author     tofuser
    public class Test extends Subclass
         public static void main(String args[])
              System.out.println("in main method");
              Test t = new Test();
              t.interfaceMethod();
         @Override
         public void interfaceMethod()
              System.out.println("interface method");
    abstract class Subclass extends JToolBar implements Interface
         private static final long serialVersionUID = 1L;
         //this line is where it breaks in my code, including it works
         //public abstract void interfaceMethod();
    interface Interface
         public abstract void interfaceMethod();
    }Edited by: hanvyj on 07-Jun-2011 03:56

  • Finalize() method being called multiple times for same object?

    I got a dilly of a pickle here.
    Looks like according to the Tomcat output log file that the finalize method of class User is being called MANY more times than is being constructed.
    Here is the User class:
    package com.db.multi;
    import java.io.*;
    import com.db.ui.*;
    import java.util.*;
    * @author DBriscoe
    public class User implements Serializable {
        private String userName = null;
        private int score = 0;
        private SocketImage img = null;
        private boolean gflag = false;
        private Calendar timeStamp = Calendar.getInstance();
        private static int counter = 0;
        /** Creates a new instance of User */
        public User() { counter++;     
        public User(String userName) {
            this.userName = userName;
            counter++;
        public void setGflag(boolean gflag) {
            this.gflag = gflag;
        public boolean getGflag() {
            return gflag;
        public void setScore(int score) {
            this.score = score;
        public int getScore() {
            return score;
        public void setUserName(String userName) {
            this.userName = userName;
        public String getUserName() {
            return userName;
        public void setImage(SocketImage img) {
            this.img = img;
        public SocketImage getImage() {
            return img;
        public void setTimeStamp(Calendar c) {
            this.timeStamp = c;
        public Calendar getTimeStamp() {
            return this.timeStamp;
        public boolean equals(Object obj) {
            try {
                if (obj instanceof User) {
                    User comp = (User)obj;
                    return comp.getUserName().equals(userName);
                } else {
                    return false;
            } catch (NullPointerException npe) {
                return false;
        public void finalize() {
            if (userName != null && !userName.startsWith("OUTOFDATE"))
                System.out.println("User " + userName + " destroyed. " + counter);
        }As you can see...
    Every time a User object is created, a static counter variable is incremented and then when an object is destroyed it appends the current value of that static member to the Tomcat log file (via System.out.println being executed on server side).
    Below is the log file from an example run in my webapp.
    Dustin
    User Queue Empty, Adding User: com.db.multi.User@1a5af9f
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    Joe
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin pulled from Queue, Game created: Joe
    User Already Placed: Dustin with Joe
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    INSIDE METHOD: false
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    User Dustin destroyed. 9
    User Joe destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    INSIDE METHOD: true
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    INSIDE METHOD: true
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    It really does seem to me like finalize is being called multiple times for the same object.
    That number should incremement for every instantiated User, and finalize can only be called once for each User object.
    I thought this was impossible?
    Any help is appreciated!

    Thanks...
    I am already thinking of ideas to limit the number of threads.
    Unfortunately there are two threads of execution in the servlet handler, one handles requests and the other parses the collection of User objects to check for out of date timestamps, and then eliminates them if they are out of date.
    The collection parsing thread is currently a javax.swing.Timer thread (Bad design I know...) so I believe that I can routinely check for timestamps in another way and fix that problem.
    Just found out too that Tomcat was throwing me a ConcurrentModificationException as well, which may help explain the slew of mysterious behavior from my servlet!
    The Timer thread has to go. I got to think of a better way to routinely weed out User objects from the collection.
    Or perhaps, maybe I can attempt to make it thread safe???
    Eg. make my User collection volatile?
    Any opinions on the best approach are well appreciated.

  • "Bad Applet class name" error while recording on Oracle Forms 11g through OpenScript (JRE 1.7.0_17)

    Hi,
    I am trying to record automation functional test script on Oracle Forms 11g using OpenScript.
    Able to open the browser, but after accessing application URL, getting application error as "Bad Applet class name"
    Java Plug-in 10.17.2.02
    Using JRE version 1.7.0_17-b02 Java HotSpot(TM) Client VM
    c:   clear console window
    f:   finalize objects on finalization queue
    g:   garbage collect
    h:   display this help message
    l:   dump classloader list
    m:   print memory usage
    o:   trigger logging
    q:   hide console
    r:   reload policy configuration
    s:   dump system and deployment properties
    t:   dump thread list
    v:   dump thread stack
    x:   clear classloader cache
    0-5: set trace level to <n>
    SSV dialog is suppressed........
    cracked oracle.forms.engine.Main
    Loading cached Forms Jars ...
    Is this version (Oracle forms 11g, JRE 1.7.0_17) supported by OATS-OpenScript ?
    Please advise if there is any work around here.
    Thanks.

    From the last OATS release notes available in the C:\OracleATS\docs directory:
    4.1 Oracle Functional Testing/OpenScript
    Oracle Functional Testing’s OpenScript scripting platform has the following system
    requirements:
    ■ Operating System (32-bit and 64-bit versions): Windows XP, Windows Vista,
    Windows 2003, Windows 7, Windows 2008, Windows 2008 R2.
    ■ Memory: Minimum 1 GB
    ■ System: x86, 32-bit or 64-bit processor, 2.6 GHz or faster
    ■ Disk Space: 4 GB minimum
    ■ Browser: Internet Explorer 7.x, 8.x., 9.x; Firefox 3.5/3.6, 6.x, 10; Chrome 27+
    (playback only).
    ■ Java Runtime Environment: JRE 1.6 minimum (up to build 38), JRE 1.7 (up to build
    11) .
    So basically, it's not supported... Can you try with another JRE version?
    As always don't forget to run OpenScript as administrator on W7/8 or equivalent
    JB

  • Windows Vista "java.lang.ClassNotFoundException: loader.class" error.

    Hello,
    Whenever I try to visit websites that have a java applet I get a dialogue with the following error:
    java.lang.ClassNotFoundException: loader.class.
    I have tried uninstalling/reinstalling java, and also adding the -xmx and -xms parameters for java applet runtime setting in control panel with various values from 128m to 1g.
    The applet at http://www.java.com/en/download/installed.jsp?detect=jre&try=1 does work and reports "CONGRATULATIONS, you have the Latest version of Java!", "Java Runtime Version 1.6.0."
    I have been experiencing this problem ever since I installed Windows Vista Home Premium a day or two ago. Any help is appreciated.
    Regards
    Greg
    =====================================
    Full output from Java Console
    =====================================
    Java Plug-in 1.6.0
    Using JRE version 1.6.0 Java HotSpot(TM) Client VM
    User home directory = C:\Users\Greg Taylor
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    p: reload proxy configuration
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    load: class loader.class not found.
    java.lang.ClassNotFoundException: loader.class
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed.
         at sun.applet.AppletClassLoader.getBytes(Unknown Source)
         at sun.applet.AppletClassLoader.access$100(Unknown Source)
         at sun.applet.AppletClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 10 more
    java.lang.ClassNotFoundException: loader.class
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed.
         at sun.applet.AppletClassLoader.getBytes(Unknown Source)
         at sun.applet.AppletClassLoader.access$100(Unknown Source)
         at sun.applet.AppletClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 10 more

    ive been having the same problems, if youve resolved this problem, please tell me.
    all help is appreciated

Maybe you are looking for

  • Connecting macbook pro to cintiq 21 ux

    is there an video adapter that'll work between the cintiq 21ux and the late 2008 macbook pro? i was wondering if there was a mini displayport to dvi-i adapter which it seems to need. thanks for your help

  • AQ: Best practice for dequeuing a queue

    Is it a good way to create a job that uses dequeue on the queue-table (each 30 second). But the procedure called in the job has an endless-Loop which runs as long as the database runs. So the job didn't restart all 30 seconds... This is the technique

  • Jdev9i;JSP;Scroll a page at the end programatically?

    Hi, How can i scroll the the page to the end? More info: I have a JSP page that shows a database table. In some condition I'd like to show the last row in the visible area when page is loaded, so if the table is large i should scroll the page program

  • Can't start J2ee server using j2sdkee1.3.1

    When i try to start j2ee server , it shows the following Error message. Exception in thread "main" java.lang.NoClassDefFoundError: javax/naming/Context at com.sun.enterprise.server.J2EEServer.<clinit>(J2EEServer.java:53) I have set all environment va

  • While trying to delete an image or header on Index page, Index..html disappeared--how could this have happened?

    Windows 7, Adobe CS6 In Dreamweaver, from files located on a USB, on the Index screen, I was trying to  1) delete an Image in order to insert a different one and link it to a page; 2) delete the Header in order to insert a border and then replace the