Java.lang.IllegalMonitorStateException problem

Hi all,
I'm using Future objects but I'm getting java.lang.IllegalMonitorStateException.
The stack trace is the following:
java.util.concurrent.ExecutionException: java.lang.IllegalMonitorStateException: current thread not owner
[java]      at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:215)
[java]      at java.util.concurrent.FutureTask.get(FutureTask.java:85)
[java]      at stock.GUI$1.mouseClicked(GUI.java:168)
[java]      at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:212)
[java]      at java.awt.Component.processMouseEvent(Component.java:5491)
[java]      at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
[java]      at java.awt.Component.processEvent(Component.java:5253)
[java]      at java.awt.Container.processEvent(Container.java:1966)
[java]      at java.awt.Component.dispatchEventImpl(Component.java:3955)
[java]      at java.awt.Container.dispatchEventImpl(Container.java:2024)
[java]      at java.awt.Component.dispatchEvent(Component.java:3803)
[java]      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
[java]      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3901)
[java]      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
[java]      at java.awt.Container.dispatchEventImpl(Container.java:2010)
[java]      at java.awt.Window.dispatchEventImpl(Window.java:1774)
[java]      at java.awt.Component.dispatchEvent(Component.java:3803)
[java]      at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
[java]      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
[java]      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
[java]      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
[java]      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
[java]      at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
[java] Caused by: java.lang.IllegalMonitorStateException: current thread not owner
[java]      at java.lang.Object.wait(Native Method)
[java]      at dsm.mrmw.ReadHandler.remoteRead(ReadHandler.java:145)
[java]      at dsm.mrmw.ReadHandler.call(ReadHandler.java:107)
[java]      at dsm.mrmw.ReadHandler.call(ReadHandler.java:28)
[java]      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:269)
[java]      at java.util.concurrent.FutureTask.run(FutureTask.java:123)
[java]      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
[java]      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
[java]      at java.lang.Thread.run(Thread.java:595)
where:
- the chunk of code in GUI.java is
try {
   Future<ISharedObject> result = memory.read(address); // the "read" call creates a ReadHandler object to satisfy the request
   try {
     SharedObject value = result.get(3, TimeUnit.SECONDS);   // line 168
     Stock s = (Stock) value.getObject();
   } catch (InterruptedException e1) {
     e1.printStackTrace();
   } catch (ExecutionException e1) {
     e1.printStackTrace();
  } catch (TimeoutException e1) {
     e1.printStackTrace();
} catch (BadAddressException e1) {
     e1.printStackTrace();
}while the chunk of code responsible for the exception in ReadHandler, a Callable object, is:
// the line 107 is the call of this method
private final ISharedObject remoteRead() throws ReadException,
     DuplicateRequestException {
          try {
                *  Creates a new destination and stores it into the
                *  subscriptions hash table.
               Subscription toSubscribe = subscribe();
               // Sends "synchronization" request ONLY if this subscription is
               // not already present.
               if (subscriptions.putIfAbsent(
                         toSubscribe.destination, toSubscribe) == null) {
                    toSubscribe.sendRequestMsg();
               if (memory.queueThread(address.toString(), this) == null) {
                    try {
                         wait(timeoutInMillisecs);   // line 145
                    } catch (InterruptedException e) {
                         Thread.currentThread().interrupt();
                    return memory.get(address);
               // else the request has already been submitted but it's still pending
               throw new DuplicateRequestException();
          } catch (NamingException e) {
               if (logger.isEnabledFor(Level.INFO)) {
                    logger.info("Unable to satisfy the remote read request: " +
                              e.getLocalizedMessage());
               throw new ReadException();
          } catch (JMSException e) {
               if (logger.isEnabledFor(Level.INFO)) {
                    logger.info("Unable to satisfy the remote read request: " +
                              e.getLocalizedMessage());
               throw new ReadException();
          } finally {
               memory.removeWaitingThread(address.getDestination());
     }How can I solve this error?
Best regards,
Michele

I'll reply by by own: the solution seems to be making the remoteRead() method synchronized (or to use a synchronized block)

Similar Messages

  • Java.lang.IllegalMonitorStateException: current thread not owner

    Hello,
    my program runs an exe that doesn't return a zero when it's finished, therefore, I can't use a waitFor().
    To solve this problem i look at the length of the file which has to be manipulated by this exe every 200ms and see whether it's length stopped changing. This should mean it's job is done...
    But using this code:
    public void run(String filename)
              System.out.println("start runtime");
              Runtime rt = Runtime.getRuntime();
              String[] callAndArgs = { "lssvmFILE.exe", filename };
              try
                   Process child = rt.exec(callAndArgs);
                   child.wait(200);
                   filesize = 0;
                   while(filesize != file.length())                            {
                        filesize = file.length();
                        child.wait(200);
                   //child.waitFor();
                   System.out.println("Process exit code is:   " + child.exitValue());
              catch(IOException e)
              {     System.err.println( "IOException starting process!");}
              catch(InterruptedException e)
              {     System.err.println( "Interrupted waiting for process!");}
              System.out.println("end run");
         }i get this on my System.out:
    Exception occurred during event dispatching:
    java.lang.IllegalMonitorStateException: current thread not owner
            at java.lang.Object.wait(Native Method)
            at LssvmFile.run(LssvmFile.java:292)
            at LssvmFile.start(LssvmFile.java:189)
            at GUI.actionPerformed(GUI.java:137)
            at java.awt.Button.processActionEvent(Button.java:329)
            at java.awt.Button.processEvent(Button.java:302)
            at java.awt.Component.dispatchEventImpl(Component.java:2593)
            at java.awt.Component.dispatchEvent(Component.java:2497)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:339)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)

    Here's the code:
    I already found out that the sleep function indeed caused this exe to run so slow. It seems that everything stops when sleep is used. By setting the delay to 2ms the duration is satisfactory (some seconds).
    I also tried skipping the sleep and just using a while, but that ended in an endless loop. Setting the delay to 1ms lead to a stop when the filelength was 0 (i guess that was on the moment that the exe cleared the file and prepared to write) so it seems to me that 2ms is quite a good trade off.
    this part of the code is preceeded by writing the data to the file and afterwards the new data will be read in again...
         //Close the stream
              outFileStream.close();
         //Run lssvmFILE.exe to compute alpha & b
              long originalfilesize = file.length();
              run(filename);
              //wait untill job done
              Thread thread = new Thread();
              long filesize = file.length();
              try{thread.sleep(2);}
              catch(InterruptedException e){};
              while(filesize != file.length() || originalfilesize ==file.length())
                   filesize = file.length();
                   try{thread.sleep(2);}
                   catch(InterruptedException e){};
         //Set up Instream (read from file)
         //----------------------Bedankt!
    Bart

  • Java.lang.IllegalMonitorStateException

    This is my code
    BatchFile b= new BatchFile();
    boolean isgenerated=b.runBatch(checkExistSub,folder);
    if(isgenerated)
    boolean runBatch(String checkExistSub, File folder)
         boolean isBatchExecuted=false;
         fold = new File(folder+"\\");
         path1= "cmd /c C:\\temp\\ps.bat \"" + checkExistSub +"\"";
         try
              Process procapplyxsl = Runtime.getRuntime().exec(path1,null,fold);
              wait(1000);
              isBatchExecuted= true;
         catch(InterruptedException inte)
         catch(IOException ioe)
         return isBatchExecuted;
    Why am I getting the following error
    Exception in thread "main" java.lang.IllegalMonitorStateException: current thread not owner
    at java.lang.Object.wait(Native Method)
    at BatchFile.runBatch(BatchFile.java:117)
    at Main.execute(Main.java:459)
    at Main.main(Main.java:488)
    Java Result: 1

    I got the solution. Thanks to everyone.
    Message was edited by:
    Simmy

  • Synchronizing unrelated threads - java.lang.IllegalMonitorStateException

    Hi,
    I'm trying to synchronize two unrelated threads using a third object, but getting java.lang.IllegalMonitorStateException: current thread not owner error. Does any one know what am I doing wrong and how to fix it. A simulated code is posted below.
    Thanks in advance.
    // ----------- beginning of code --------------------------
    // Code that throws java.lang.IllegalMonitorStateException: current thread not owner error.
    public class ThreadTest
    public static void log( String message )
         System.out.println( Thread.currentThread().getName() + ":" + message );
    public static void main( String args[] )
         Thread thread1 = new Thread1();
         Thread thread2 = new Thread2();
         thread1.start();
         thread2.start();
         try
         thread1.join();
         thread2.join();
         catch (InterruptedException e)
         e.printStackTrace();
         log( "All Done...");
    class Thread1 extends Thread
    public void run()
         synchronized( Common.done )
         while (!Common.done.booleanValue())
              ThreadTest.log("Waiting on Common.done");
              try
              Common.done.wait();
              catch (InterruptedException e)
              e.printStackTrace();
    class Thread2 extends Thread
    public void run()
         synchronized( Common.done )
         ThreadTest.log( "Sleeping for 10 seconds ");
         try
              Thread.sleep( 10 * 1000 );
         catch (InterruptedException e)
              e.printStackTrace();
         ThreadTest.log( "Calling notifyAll");
         Common.done = Boolean.TRUE;
         // ******* Why am I getting 'java.lang.IllegalMonitorStateException: current thread not owner' in the next line
         Common.done.notifyAll();
    class Common
    public static Boolean done = Boolean.FALSE;
    // ----------- end of code --------------------------

    // ******* Why am I getting'java.lang.IllegalMonitorStateException:
    current thread not owner' in the next line
    Common.done.notifyAll(); Because x.notifyAll() has to be inside a
    synchronized(x) block.
    The code you posted looks like it meets that
    criteria, so I would have to conclude the code you
    posted does not represent the actual code you are
    running.Hi.. It is inside synchronized( Common.done) block... Thats why I'm confused....

  • Java.lang.ClassCastException problem with ApplicationModuleImpl

    Hi, to whom this may be familiar:
    This is from a oracle.adf.controller.struts.actions.DataAction class:
    public class SwitchDAAction extends DataAction
      protected void findForward(DataActionContext actionContext) throws Exception
        super.findForward(actionContext);
        ZBModuleImpl svc = (ZBModuleImpl) actionContext.getBindingContext().findDataControl("ZBModuleDataControl").getDataProvider();
        BillViewImpl oneUser = svc.getBillView1();
    ...ZBModuleImpl is an application module which extends oracle.lbo.server.ApplicationModuleImpl.
    As the last statement indicates, the purpose is to obtain an instance of a view object that is already in the application.
    There is no error at compilation. However, when the application runs, the embedded oc4j gives an error:
    WARNING: Unhandled Exception thrown: class java.lang.ClassCastExceptionand in the browser the first line in the "500 Internal Server Error", shown below, pin-points to the line of code that cast Object to ZBModuleImpl:
    at zb.view.SwitchDAAction.findForward(SwitchDAAction.java:18)I broke up the line into multiple lines to see where exactly the problem is:
    public class SwitchDAAction extends DataAction
      protected void findForward(DataActionContext actionContext) throws Exception
        super.findForward(actionContext);
        BindingContext bdCtx = actionContext.getBindingContext();
        DCDataControl dc = bdCtx.findDataControl("ZBModuleDataControl");
        Object dpd = dc.getDataProvider();
        ZBModuleImpl svc = (ZBModuleImpl) dpd;
        BillViewImpl oneUser = svc.getBillView1();
    ...The error messages always point to that line that does data type casting.
    What is the problem and what can be done to fix it? (I am using JDeveloper 10.1.2.0.0).
    Thanks for your help!
    Newman

    Hi, Valery and Anton:
    Sorry I did not mention the version of Jdev I am using in my last posting. It is 10.1.2. It is so precious someone around still know the older versions.
    Anton, since mine is an older version, I tried to set the custom properties. The name of my application is ZB and the name of the application module is ZBModuleImpl. The name of the view object I am trying to get an instance of is BillViewimpl.
    In the Application Module Editor for ZBModule, at the Custom Properties node, there are names for three properties in the drop-down list: DESCRIPTION, FILE_NAME, DATA_CONTROL_NAME. Not knowing what they are and what they are for, I tried to add two name/value pairs: DESCRIPTION/ZB and DATA_CONTROL_NAME/ZBModuleDataControl. And for the last method on the problem line of code I tried both getDataProvider() and getApplicationModule(), in the following combinations, and none of them work out:
                                                   getDataProvider()     getApplicationModule()
    DESCRIPTION/ZB (only)                                   X                       X
    DATA_CONTROL_NAME/ZBModuleDataControl (only)            X                       X
    (both)                                                  X                       XPlease correct me where I did wrong. I wonder what oracle.jbo.common.ws.WSApplicationModuleImpl is. I even tried
    BillViewImpl oneUser = (ZBModuleImpl) actionContext.getBindingContext().findDataControl("ZBModuleDataControl").getApplicationModule().findApplicationModule("ZBModuleImpl");
    and
    BillViewImpl oneUser = ((ZBModuleImpl) actionContext.getBindingContext().findDataControl("ZBModuleDataControl").getApplicationModule()getApplicationModule()).findViewObject("BillViewImpl");But the problem is always with the typecasting from ApplicationModule to ZBModuleImpl. Is there anything that WSApplicationModuleImpl can do to help out?
    Thanks a lot for your help!
    Newman

  • Java.lang.NullPointerException problem after installation

    Dear all,
    after i install the EP6.0 SP9 on AIX 5.3 ORACLE 9.2 ,when i want to create role ,i hit the IE error message like "operation aborted" .in the log viewer i found the error
    Time : 16:26:50:119
    Category : /System/Server
    Date : 06/22/2005
    Message :  [com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorCompContextHandler] getPriority() failed
    [EXCEPTION]
    java.lang.NullPointerException
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJndi.getPriority(RoleEditorJndi.java:1622)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJsTree.createTreeNode(RoleEditorJsTree.java:784)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJsTree.getChildTreeNodes(RoleEditorJsTree.java:646)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJsTree.createJScriptTree(RoleEditorJsTree.java:96)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJsTree.createJScriptTree(RoleEditorJsTree.java:106)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorJsTree.buildRoleEditorJsTree(RoleEditorJsTree.java:56)
    at com.sapportals.portal.pcd.admintools.roleeditor.misc.RoleEditorPage2.createContentStudioPage2(RoleEditorPage2.java:1501)
    at com.sapportals.portal.pcd.admintools.roleeditor.misc.RoleEditorPage2.createPage2(RoleEditorPage2.java:1425)
    at com.sapportals.portal.pcd.admintools.roleeditor.RoleEditorMain.doContent(RoleEditorMain.java:129)
    at com.sapportals.portal.prt.component.AbstractPortalComponent.serviceDeprecated(AbstractPortalComponent.java:209)
    at com.sapportals.portal.prt.component.AbstractPortalComponent.service(AbstractPortalComponent.java:114)
    at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
    at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
    at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
    at com.sapportals.portal.prt.component.PortalComponentResponse.include(PortalComponentResponse.java:215)
    at com.sapportals.portal.prt.pom.PortalNode.service(PortalNode.java:646)
    at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
    at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
    at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
    at com.sapportals.portal.prt.core.PortalRequestManager.runRequestCycle(PortalRequestManager.java:753)
    at com.sapportals.portal.prt.connection.ServletConnection.handleRequest(ServletConnection.java:232)
    at com.sapportals.portal.prt.dispatcher.Dispatcher$doService.run(Dispatcher.java:522)
    at java.security.AccessController.doPrivileged1(Native Method)
    it seems to be java problem ,anybody could give some suggestion?thanks

    Hi,
    I have similar problem.
    If you have solved this issue please let me know how.
    Thanks
    Arun

  • Java.lang.StackOverflowError problem, drawing images in applet :(

         * Paints the applet
        @Override
        public void paint(Graphics g)
            if(running && levelOne)
            g.setColor(Color.MAGENTA);
            g.drawString("HP Left: " + player.getHP(), 100, 10);
    //      g.drawString("Time Left: " + timer.getTime(), 170, 10);
            g.drawString("Score: " + player.getScore(), 30, 10);
            g.drawString("Required Score To Next Level: " + player.getScore() + "/3000", 100, 190);
            g.drawString("Level: 1", 30, 190);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
            if(start && storyStarted)
                try
                    update(g);
                    paintStory();
                catch(java.lang.StackOverflowError sofe)
                    System.exit(0);
            else if(start)
                g.drawImage(image, 0, 0, this);
                g.drawImage(gun, 200, 400, this);
         * Updates the paint() method and the applet
        @Override
        public void update(Graphics g)
            if(dbImage == null)
                dbImage = createImage(this.getWidth(), this.getHeight());
                dbG = dbImage.getGraphics();
            dbG.setColor(getBackground());
            dbG.fillRect(0, 0, this.getWidth(), this.getHeight());
            dbG.setColor(getForeground());
            paint(dbG);
            g.drawImage(dbImage, 0, 0, this);
        public void paintStory()
            getGraphics().drawImage(story1, 0, 0, this);
        }I know that my problem appears somewhere in the above written code, so if you would take a look, and try to help me fixing my problem! :D

    Vimsie wrote:
    I get a StackOverflowError, but the image isn't flickering!Err, the image is not flickering because there are no repaints happening anymore due to the StackOverflowError. This is hardly an argument for your approach.
    However, I have to admit I don't know how to solve your flickering problem. I've never used AWT but always SWING (but then I don't do applets).
    Maybe google can help?

  • Another java.lang.NoClassDefFoundError problem

    C:\tinyos\cygwin\opt\tinyos-1.x\contrib\cotsbots\tools>java -jar RobotCmdGUI.jar
    RobotCmdGUI: Using group ID 125
    Exception in thread "main" java.lang.NoClassDefFoundError: RobotCmd/RobotCmdGUI$
    1
    at RobotCmd.RobotCmdGUI.initComponents(RobotCmdGUI.java:158)
    at RobotCmd.RobotCmdGUI.<init>(RobotCmdGUI.java:55)
    at RobotCmd.RobotCmdGUI.main(RobotCmdGUI.java:936)
    C:\tinyos\cygwin\opt\tinyos-1.x\contrib\cotsbots\tools>
    My main-class is RobotCmdGUI which I have included in my manifest as -
    Main-Class: RobotCmd.RobotCmdGUI
    The directory to my main class file is as follows:
    C:\tinyos\cygwin\opt\tinyos-1.x\contrib\cotsbots\tools\RobotCmd\RobotCmdGUI.class
    I wonder what else could be the problem and why there's a $1 in "Exception in thread "main" java.lang.NoClassDefFoundError: RobotCmd/RobotCmdGUI$1" since my main class file is RobotCmdGUI
    Thanks again

    I wonder what else could be the problem and why
    there's a $1 in "Exception in thread "main"
    java.lang.NoClassDefFoundError:
    RobotCmd/RobotCmdGUI$1" since my main class file is
    RobotCmdGUI
    The RobotCmd/RobotCmdGUI$1 represents an annonymous class inside the RobotCmdGUI class - probably a listener of some sort. This must be present inside the jar - it sounds like you did not put it in the jar. You can check the contents of the jar using "jar tf RobtCmdGUI.jar"

  • How to solve this? java.lang.IllegalArgumentException problem

    The midlet compliled successfully..
    Once run,
    I enter 3 different records...
    then after when I 'VIEW' for example I enter recordID: 1..
    by right, all the details about recordId : 1 would be listed out...somehow, this error pops up.
    java.lang.IllegalArgumentException
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.rms.*;
    * @author RyanLCC
    public class cdSeller extends MIDlet implements CommandListener{
    private Display display;
    private Form form;
    private Command add, view, update, delete, exit;
    private TextField rcdId, title, quantity, price, profit, director, publish, actors;
    private RecordStore rs;
    private Alert alert = new Alert("New Data Added !!!");
    private Alert alert1 = new Alert("Database Upated!!!");
    private Alert alert2 = new Alert("Record Deleted!!!");
    private Alert alert3 = new Alert("Looking Data!!!");
    public cdSeller()throws RecordStoreException{
    display = Display.getDisplay(this);
    exit = new Command("Exit", Command.EXIT, 1);
    add = new Command("Add",Command.SCREEN,2);
    update = new Command("Update",Command.SCREEN,2);
    delete = new Command("Delete",Command.SCREEN,2);
    view = new Command("View",Command.SCREEN,2);
    rcdId= new TextField("Record ID :","",5,TextField.NUMERIC);
    title= new TextField("Title :","",11,TextField.ANY);
    quantity= new TextField("Quantity :","",8,TextField.NUMERIC);
    price= new TextField("Retail price :","",8,TextField.ANY);
    profit= new TextField("Profit margin:","",8,TextField.ANY);
    director= new TextField("Director :","",11,TextField.ANY);
    publish= new TextField("Publisher :","",11,TextField.ANY);
    actors= new TextField("Actors :","",11,TextField.ANY);
    rs = RecordStore.openRecordStore("My CD Datbase Directory", true);
    form = new Form("My CD Database");
    form.append(rcdId);
    form.append(title);
    form.append(quantity);
    form.append(price);
    form.append(profit);
    form.append(director);
    form.append(publish);
    form.append(actors);
    form.addCommand(exit);
    form.addCommand(add);
    form.addCommand(update);
    form.addCommand(delete);
    form.addCommand(view);
    form.setCommandListener(this);
    public void startApp() {
    display.setCurrent(form);
    public void pauseApp() {
    public void destroyApp(boolean unconditional) {
    try {
    rs.closeRecordStore();
    } catch (RecordStoreException ex) {
    ex.printStackTrace();
    public void commandAction(Command c, Displayable d) {
    alert.setTimeout(3000);
    alert1.setTimeout(3000);
    String str;
    byte bytes[];
    int recordID;
    try{
    if(c==add){
    str = title.getString()+":"+quantity.getString()+
    ":"+price.getString()+":" +profit.getString()+
    ":"+director.getString()+":"+publish.getString ()+
    ":"+actors.getString();
    bytes=str.getBytes();
    recordID = rs.addRecord(bytes, 0, bytes.length);
    System.out.println("Record of ID:"+recordID+" is added");
    Display.getDisplay(this).setCurrent(alert);
    }else if(c==update){
    recordID = Integer.parseInt(rcdId.getString());
    str = title.getString()+":"+quantity.getString()+
    ":"+price.getString()+":" +profit.getString()+
    ":"+director.getString()+":"+publish.getString ()+
    ":"+actors.getString();
    bytes=str.getBytes();
    rs.setRecord(recordID, bytes, 0, bytes.length);
    Display.getDisplay(this).setCurrent(alert1);
    }else if(c == delete){
    recordID = Integer.parseInt(rcdId.getString());
    rs.deleteRecord(recordID);
    Display.getDisplay(this).setCurrent(alert2);
    }else if(c == view ){
    recordID = Integer.parseInt(rcdId.getString());
    bytes = new byte[rs.getRecordSize(recordID)];
    rs.getRecord(recordID,bytes,0);
    String str1 = new String(bytes);
    int index = str1.indexOf(":");
    title.setString(str1.substring(0));
    quantity.setString(str1.substring(1));
    price.setString(str1.substring(2));
    profit.setString(str1.substring(3));
    director.setString(str1.substring(4));
    publish.setString(str1.substring(5));
    actors.setString(str1.substring(6));
    }else if( c == exit){
    destroyApp(true);
    notifyDestroyed();
    }catch(Exception e){
    e.printStackTrace();
    }

    *To change this template, choose Tools | Templates*
    and open the template in the editor.
    *import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;*
    *import javax.microedition.rms.*;
    *@author RyanLCC*
    public class CdSeller extends MIDlet implements CommandListener{
        private Display display;
        private Form form;
        private Command add, view, update, delete, exit;
        private TextField rcdId, title, quantity, price, profit, director, publish, actors;
        private RecordStore rs;
        private Alert alert = new Alert("New Data Added !!!");
        private Alert alert1 = new Alert("Database Upated!!!");
        private Alert alert2 = new Alert("Record Deleted!!!");
        private Alert alert3 = new Alert("Looking Data!!!");
        public CdSeller()throws RecordStoreException{
        display = Display.getDisplay(this);
        exit = new Command("Exit", Command.EXIT, 1);
        add = new Command("Add",Command.SCREEN,2);
        update = new Command("Update",Command.SCREEN,2);
        delete = new Command("Delete",Command.SCREEN,2);
        view = new Command("View",Command.SCREEN,2);
        rcdId= new TextField("Record ID     :","",5,TextField.NUMERIC);
        title= new TextField("Title         :","",11,TextField.ANY);
        quantity= new TextField("Quantity   :","",8,TextField.ANY);
        price= new TextField("Retail price  :","",8,TextField.ANY);
        profit= new TextField("Profit margin:","",8,TextField.ANY);
        director= new TextField("Director   :","",11,TextField.ANY);
        publish= new TextField("Publisher   :","",11,TextField.ANY);
        actors= new TextField("Actors       :","",11,TextField.ANY);
        rs = RecordStore.openRecordStore("My CD Datbase Directory", true);
        form = new Form("My CD Database");
        form.append(rcdId);
        form.append(title);
        form.append(quantity);
        form.append(price);
        form.append(profit);
        form.append(director);
        form.append(publish);
        form.append(actors);
        form.addCommand(exit);
        form.addCommand(add);
        form.addCommand(update);
        form.addCommand(delete);
        form.addCommand(view);
        form.setCommandListener(this);
        public void startApp() {
            display.setCurrent(form);
        public void pauseApp() {
        public void destroyApp(boolean unconditional) {
            try {
                rs.closeRecordStore();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
        public void commandAction(Command c, Displayable d) {
            alert.setTimeout(3000);
            alert1.setTimeout(3000);
            String str;
            byte bytes[];
            int recordID;
            try{
                if(c==add){
                    str = title.getString()+":"+quantity.getString()+
                          ":"+price.getString()+":" +profit.getString()+
                          ":"+director.getString()+":"+publish.getString()+
                          ":"+actors.getString();+
    +                bytes=str.getBytes();+
    +                recordID = rs.addRecord(bytes, 0, bytes.length);+
    +                System.out.println("Record of ID:"+recordID+" is added");
                    Display.getDisplay(this).setCurrent(alert);
                }else if(c==update){
                    recordID = Integer.parseInt(rcdId.getString());
                    str = title.getString()+":"+quantity.getString()+
                          ":"+price.getString()+":" +profit.getString()+
                          ":"+director.getString()+":"+publish.getString()+
                          ":"+actors.getString();+
    +                bytes=str.getBytes();+
    +                rs.setRecord(recordID, bytes, 0, bytes.length);+
    +                System.out.println("Record of ID:"+recordID+" is updated");
                    Display.getDisplay(this).setCurrent(alert1);
                }else if(c == delete){
                    recordID = Integer.parseInt(rcdId.getString());
                    rs.deleteRecord(recordID);
                    System.out.println("Record of ID:"+recordID+" is deleted");
                    Display.getDisplay(this).setCurrent(alert2);
                }else if(c == view ){
                    recordID = Integer.parseInt(rcdId.getString());
                    bytes = new byte[rs.getRecordSize(recordID)];
                    rs.getRecord(recordID,bytes,0);
                    String str1 = new String(bytes);
                    int index = str1.indexOf(":");
                    title.setString(str1.substring(0));
                    quantity.setString(str1.substring(1));
                    price.setString(str1.substring(2));
                    profit.setString(str1.substring(3));
                    director.setString(str1.substring(4));
                    publish.setString(str1.substring(5));
                    actors.setString(str1.substring(6));
            }else if( c == exit){
                destroyApp(true);
                notifyDestroyed();
        }catch(Exception e){
            e.printStackTrace();
    Starting emulator in execution mode
    Installing suite from: http://127.0.0.1:59543/RecordStore.jad
    Record of ID:1 is added
    Record of ID:2 is added
    java.lang.IllegalArgumentException
    at javax.microedition.lcdui.TextField.setCharsImpl(), bci=79
    at javax.microedition.lcdui.TextField.setString(), bci=37
    at CdSeller.commandAction(CdSeller.java:120)
    at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
    at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
    at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
    at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=170
    at com.sun.midp.chameleon.CWindow.pointerInput(), bci=76
    at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
    at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
    at com.sun.midp.events.EventQueue.run(), bci=179
    at java.lang.Thread.run(Thread.java:619)
    javacall_lifecycle_state_changed() lifecycle: event is JAVACALL_LIFECYCLE_MIDLET_SHUTDOWNstatus is JAVACALL_OK
    I had tired to change the quantity= new TextField("Quantity   :","",8,TextField.ANY);+ but still giving me the same problem...
    Here again..Thankx alot..

  • Unable to read big files into string object & java.lang.OutOfMemory Problem

    Hi All,
    I have an application that uses applet and servlet communication. On the client side I am reading an large xml file of 12MB size (using JFileChooser) and converting the file to an string object using below code. But I am getting java.lang.OutOfMemory on the client side . But the same below code works fine for small xml files which are less than 4MB sizes:
    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF8"), 1024*12);
    String s, s2 = new String();
    while((s = in.readLine())!= null)
    s2 += s + "\n";
    I even tried the below code but still java.lang.OutOfMemory is coming:
    while (true)
    int i = in.read();
    if (i == -1)
    break;
    sb.append(i);
    Please let me know what am I doing wrong here ...

    Hi,
    I could avoid the java.lang.OutOfMemory error using below code. But using below code I could read small files of sizes less than 4MB
    but with large files of 12 MB the below code just simply hangs and I am unable to print the string object namely 's'.
    My purpose is to construct an String or StringBuffer object out the user uploaded xml file at the client side and pass that object to server for processing. So how can I construct such object avoid memory problem and increasing the performance of such operations.
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    String s = new String(b, 0, b.length);
    in.close();
    Thanks & Regards,
    Sony.

  • Java.lang.Exception problem .. help needed

    I have a class and i am trying to access a method of another class that is reading an object.
    public void read(String filename) throws Exception {
    String fn = filename;
    ObjectInputStream out = null;
    Object object = null;
    try {
    FileInputStream file = new FileInputStream(fn);
    out = new ObjectInputStream(file);
    object = out.readObject();
    out.close();
    } catch (java.io.IOException IOE) {
    if (out != null)
    try {
    out.close();
    } catch (Exception ex) {}
    throw IOE;
    When i am compiling the program it is giving me this error
    unreported exception java.lang.Exception; must be caught or declared to be thrown
    I'm quite new to java ... could you tell me how to catch this exception
    its in this part
    scoreTable.read("scores.txt");
    Thanks

    Try this :
        private void someMethod(){
            try{
                read("c:\\bank\\testobject.txt");
            }catch(IOException ex){
                ex.printStackTrace();
            }catch(ClassNotFoundException ex){
                ex.printStackTrace();
    //        you can use the object here
        Object object;
        public void read(final String filename)  throws IOException, ClassNotFoundException{
            ObjectInputStream out = null;
            object = null;
            try{
                out = new ObjectInputStream(new FileInputStream(filename));
                object = out.readObject();
            }finally{
                if( out != null ){
                    out.close();
        }

  • Java.lang.NullPointerException problems

    I have noticed i cannot make a Point P = new Point(null); it throws this exception. However i have made a function that returns a point, or null, depending on whether two line segments collide. Here is what happens:
    this is where the error occours, and where i need to use the method:
    if (LineIntersect(variables) != null);
         Point P = new Point(LineIntersect(variables) );
            // do whatever i need
    }with the method along the lines of:
    Point LineIntersect(variables)
            if (collides)
                Point P = new Point();
                   //P = whatever i want....
            else
                   return null;
    }however i get an java.lang.NullPointerException at
    Point P = new Point(LineIntersect(variables) );
    and i dont know why, as i am only declairing this if LineIntersect(variables) is NOT null.... I dont think this is a syntax error, will post more code if needed
    thanks for the help!

    My 0.02c
    You are calling the LineIntersect method (should be lineIntersect) twice. Plus that method returns a Point object so no need to use the new operator again. I would do this:
    Point p = lineIntersect(variables);
    if(p != null) {
        // do something with the Point
    }

  • SetLookAndFeel and java.lang.ClassNotFoundException problem

    Hi there, I'll admit I'm a newbie, but I really need help. I'm trying to create a GUI with a Metal layout: here the code:
    public static void main(String[] argument) {
    UIManager.setLookAndFeel
    ("javax.swing.plaf.metal.MetalLookAndFeel");
    when I try to compile the file, it gives following error:
    unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    UIManager.setLookAndFeel
    ("javax.swing.plaf.metal.MetalLookAndFeel");
    ^
    please remember i'm a newbie, so go easy on the lingo

    import javax.swing.*;
    import java.awt.*;
    public class MainFrame extends JFrame {
         public MainFrame() {
              super("Vloot Verslag 2006");
              setSize(350, 100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              Container pane = getContentPane();
              FlowLayout flo = new FlowLayout();
              pane.setLayout(flo);
              JButton Accounting = new JButton("Accounting");
              Accounting.setEnabled(false);
              JButton Logistics = new JButton("Logistics");
              JButton Exit = new JButton("Exit");
              pane.add(Accounting);
              pane.add(Logistics);
              pane.add(Exit);
              setContentPane(pane);
         public static void main(String[] argument) {
              UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              MainFrame sal = new MainFrame();
    Ok there is my whole file, I just need to know what I am doing wrong

  • Java.lang.IllegalArgumentException (problem when playing audio)

    i play an audio with code like this:
    private AudioFormat getAudioFormat(){
        float sampleRate = 16000;
        //8000,11025,16000,22050,44100
        int sampleSizeInBits = 16;
        //8,16
        int Channels =2;
        //1,2
        boolean Signed =true;
        //true,false
        boolean bigEndian = false;
        //true,false
        return new AudioFormat(sampleRate,
                               sampleSizeInBits,
                               Channels,
                               Signed,
                               bigEndian);
      }//end getAudioFormat
    private void playAudio() {
        try{
          audioFormat = getAudioFormat();
          //System.out.println(audioFormat);
          //tformat.setText(audioFormat.toString());
          DataLine.Info dataLineInfo =
                              new DataLine.Info(
                                SourceDataLine.class,
                                        audioFormat);
          sourceDataLine =
                 (SourceDataLine)AudioSystem.getLine(
                                       dataLineInfo);
        }catch (Exception e) {
           JOptionPane.showMessageDialog(null, e.getMessage(),"Message",JOptionPane.ERROR_MESSAGE);
        }//end catch
      }//end playAudio
      //begin playing
    playAudio();
    int cnt=1; 
    byte dt[]=new byte[1000];     
        try{
                sourceDataLine.open(audioFormat,sourceDataLine.getBufferSize());
                  sourceDataLine.start();
         }catch(LineUnavailableException e){
                 e.printStackTrace();
          do { // process messages sent from client    
             try {     
                cnt=sourceDataLine.read(dt,0,dt.length);
                if(cnt > 0){
              sourceDataLine.write(
                                 temp1, 0, cnt);
             catch(IllegalArgumentException ex){
                ex.printStackTrace();
          } while ( cnt!=-1 );when i playing a few minutes i got bug like this
    java.lang.IllegalArgumentException: illegal request to write non-integral number of frames (450 bytes, frameSize = 4 bytes). please tell me what wrong?
    Edited by: Christian_info on Jun 13, 2008 1:25 AM

    i play an audio with code like this:
    private AudioFormat getAudioFormat(){
        float sampleRate = 16000;
        //8000,11025,16000,22050,44100
        int sampleSizeInBits = 16;
        //8,16
        int Channels =2;
        //1,2
        boolean Signed =true;
        //true,false
        boolean bigEndian = false;
        //true,false
        return new AudioFormat(sampleRate,
                               sampleSizeInBits,
                               Channels,
                               Signed,
                               bigEndian);
      }//end getAudioFormat
    private void playAudio() {
        try{
          audioFormat = getAudioFormat();
          //System.out.println(audioFormat);
          //tformat.setText(audioFormat.toString());
          DataLine.Info dataLineInfo =
                              new DataLine.Info(
                                SourceDataLine.class,
                                        audioFormat);
          sourceDataLine =
                 (SourceDataLine)AudioSystem.getLine(
                                       dataLineInfo);
        }catch (Exception e) {
           JOptionPane.showMessageDialog(null, e.getMessage(),"Message",JOptionPane.ERROR_MESSAGE);
        }//end catch
      }//end playAudio
      //begin playing
    playAudio();
    int cnt=1; 
    byte dt[]=new byte[1000];     
        try{
                sourceDataLine.open(audioFormat,sourceDataLine.getBufferSize());
                  sourceDataLine.start();
         }catch(LineUnavailableException e){
                 e.printStackTrace();
          do { // process messages sent from client    
             try {     
                cnt=sourceDataLine.read(dt,0,dt.length);
                if(cnt > 0){
              sourceDataLine.write(
                                 temp1, 0, cnt);
             catch(IllegalArgumentException ex){
                ex.printStackTrace();
          } while ( cnt!=-1 );when i playing a few minutes i got bug like this
    java.lang.IllegalArgumentException: illegal request to write non-integral number of frames (450 bytes, frameSize = 4 bytes). please tell me what wrong?
    Edited by: Christian_info on Jun 13, 2008 1:25 AM

  • PaintComponent()  and jave.lang.OutOfMemoryError problem

    I have a paintComponent() method that in it , I paint the GraphicsContexts with a big BufferedImage
    here is the code:
    void doPaint(){ //do some painting on the buffer
    buffer = new BufferedImage(waveForm.viewPortDim.width,waveForm.viewPortDim.height,
    BufferedImage.TYPE_4BYTE_ABGR_PRE);
    waveForm.xPanel.paintEcgBuffer(buffer);
    public void paintComponent(Graphics g){
    //super.paintComponent(g);//??
    Graphics2D g2 = (Graphics2D)g;
    try{            
    g2.drawImage(buffer,0,0,this);
    }catch(OutOfMemoryError e){
    e.printStackTrace();
    System.out.println("error "+e.getMessage());
    I use doPaint() to do some painting over the buffer but i get jave.lang.OutOfMemoryError when i try to do
    g2.drawImage(buffer,0,0,this);
    Is there a limit on the height or width of the GraphicsContexts?
    The dimension of the bufeer can be about 1400x2800 or 1400x5500.
    What can I do?
    Thank you in advance.
    Yair.

    I don't know the answer to this question, but it may help you out to examine it.
    Is it possible that your graphics card is running out of the memory to display this large image?
    You may want to just display what the screen is displaying, so clip the rest beforehand, which would lead to a smaller buffered image.

Maybe you are looking for

  • Error in ChartImage.axd - Image not Found

    I am getting an intermitant error on our production website.  I have a web form with two pie charts & every once in a while i will get an error from /ChartImg.axd: The image is not found.    at    System.Web.UI.DataVisualization.Charting.ChartHttpHan

  • Servicegen issue with binding webservices.jar

    Hey, I am trying to build a ejb webservice using ant and servicegen. When I run it, it blows up and gives me a ton of binding errors. The problem is the binding errors are on files from the webservices.jar not from my jar. What is wrong with my scrip

  • Query regarding Freight

    Hi! Gurus, I am having a query regarding Freight . Consider PO having 100 Quantity and freight applicable WRT quantity Condition type FRC1.Rs 1 /1 Quantity. Freight amount = Rs 100. Consider 5 Good Receipt WRT purchase order. GR1- 20 Quantity ,Freigh

  • Need Help in Select Statement

    Dear gurus Below is my select statement. Im having problem with statement. the problem is that  the table vbfa  have some entries like this 800     1400004654     10     3900012235     10     M     424,672.68 800     1400004654     10     3900012257 

  • Reader plugin with CHtmlView (MFC's WebBrowser control)

    Can anyone from Adobe tell me if using the Reader plug-in within a CHtmlView (MFC's WebBrowser control) is supported? I found a KB stating that the .NET control isn't supported (http://helpx.adobe.com/acrobat/kb/using-acropdf-dll-within-microsoft.htm