Help please: static instance of a class

Hello guys,
I'm quite new to Java (I had abandonned it for years, and now i'm recovering the good habbits) and i am finding trouble with an static instance of a class.
The thing is that I created a JSP page that calls a Java class. My JSP page will be reloaded several times for one same user, therefore, every teme the JSP page is reloaded, a new instance of my Java class is created.
Since I NEEDED to always have the same object of my Java class, I decided to create an static instance of this class. The snippet of my class is:
public class MyClass{
     private static MyClass instance = null;
     private Vector v=null;
     private myClass(){
     v = new Vector();     
public Vector getItems() {
     return this.v;
public static MyClass getInstance() {
          if(instance == null) {
          instance = new MyClass();
          return instance;
For the first time I call getInstance() I get a new instance of MyClass, and if i'm not wrong, the following times I call getInstance(), I should get the same instance, right???
The thing is that I implemented another method that changes the value of Vector v. But when calling this method from the static instance, the change is never reflected on Vector v (every time I try to recover the value of v I get a Null Pointer Exception)
Could anyone tell me what i am doing wrong, please?Is there any other way to do this??
Thanx in advance
Sergio

thanks for the answers, but now I have two questions
instead of one:
import java.util.Vector;
public class TestSingleton {
    public static void main(String[] args) throws Exception {
        MyClass clazz = MyClass.getInstance();
        System.out.println("#" +clazz);
        clazz.addItem("Test");
        clazz.addItem("Hello!");
        Vector vec = clazz.getItems();
        System.out.println(vec.size());
class MyClass{
    private static MyClass instance = null;
    private Vector v=null;
    private MyClass() {
        v = new Vector();
    public Vector getItems() {
        return this.v;
    public void addItem(Object obj) {
        this.v.add(obj);
    public static synchronized MyClass getInstance() {
        if(instance == null) {
            instance = new MyClass();
        return instance;
}Take a look at this code and see if this answers both your questions.
I love it when the questions multiply! :)

Similar Messages

  • Calling an instance of a class please help

    Hi all,
    I hope this is the right forum to post this topic.I am doing so cause I am dealing with servlets.In the init() method of a servlet.I want to call an instance of another class UserPresent.java .I will post the code below
    public void init() {
    UserPresent userpresent = new UserPresent();
    userpresent.initDatabase();
    }The compiler keeps complaining saying that .......
    AuthenticateServlet21.java:12: cannot resolve symbol
    symbol : class UserPresent
    location: class package1.structure.AuthenticateServlet21
    UserPresent userpresent = new UserPresent();
    I have included the package package1.structure in both the servlet code and the UserPresent code.
    Kindly let me know what could be the problem.
    Help would be appreciated
    Thanks
    AS

    The compiler can't find the UserPresent class in your servlet.
    You may need to import it ie import package1.structure.UserPresent
    What package is the UserPresent class in? What package is your servlet in? Is your class public?

  • Help with loading dynamic classes ..need help please

    i'm trying to design a program where by i can load dynamic classes
    the problem i'm getting is that only one class is loading.
    classes are loaded by their names,and index numbers of public methods from a linklist
    .When the program runs only the first class is ever loaded and only the methods of that class ..
    help please
    //class loader
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test2 extends Thread
         public Class c;
         public Class Ray;
         public Class[] x;
         public static Object object = null;
         public Method[] theMethods;
         public static Method[] method,usemethod;
         public int methodcount;
         public static int MethodCt;     
         public static JList list;
    public Method[] startClass(String SetMethodName)
         try
              c = Class.forName(SetMethodName);
              object = c.newInstance();
              theMethods = c.getDeclaredMethods();
              // number of methods
              //methodcount = theMethods.length;
         catch (Exception e)
              e.printStackTrace();
    // return the array then invoke the particular method later
    return theMethods ;
    public void RunMethod(Method[] SomeMethod, int methodcount)
         try
              SomeMethod[methodcount].invoke( object,null );
         catch (Exception e)
              e.printStackTrace();
    // end class loader
    //main calling program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing .*;
    import java.lang.reflect.*;
    public class JFMenu extends JFrame
         public static JMenu pluginMenu;
         public static JMenuBar bar;
         public static final Test2 w = new Test2();
    public static Method[] setmethod;
    private static ClassLinkList startRef = null;
    private static ClassLinkList linkRef3 = null;
    private static ClassLinkList startRef2 = null;
    private String ClassName,ShortCut;
    private int MethodNumber;
    private JMenuItem PluginItem;
         JFMenu()
              super (" JFluro ");     
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              JMenuItem exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic('X');
              fileMenu.add(exitItem);
              exitItem.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             System.exit(0);
              JMenu pluginMenu = new JMenu("Plugins");
              pluginMenu.setMnemonic('P');
              startRef = new ClassLinkList ("Hello","Hello ",2,1926,"Painter");
              addToList("Foo","Foo ",0,1930,"Author");
              while (startRef.linkRef5 != null)
                   //pluginMenu.addSeparator();
                   ClassName = startRef.linkRef5.className;
                   ShortCut = startRef.linkRef5.shortcutName;
    MethodNumber = startRef.linkRef5.methodNumber;
    AddMenuItem(pluginMenu,ShortCut,ClassName,MethodNumber);
                   startRef.linkRef5 = startRef.linkRef5.next;
              // create menu bar and add JFMenu window to it
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);
              bar.add(pluginMenu);
              //attributes for JFMenu frame
              setSize(500,200);
              setVisible(true);
         }// end JFMenu constructor
         public void AddMenuItem(JMenu MainMenu, String shortcut,String className, final int methodCount )
              if (MainMenu==null)
                   return;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              setmethod = w.startClass(className);
              item.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         public JMenuItem AddMenuItem2(JMenu MainMenu, String shortcut)
              //if (MainMenu==null)
              //     return Main;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              //setmethod = w.startClass(className);
              //item.addActionListener(this);
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         return item;
         public void ReloadMenu(JMenuBar Bar, JMenu PluginMenu)
              if (Bar==null)
                   return;
              //     setJMenuBar(Bar);
              Bar.add(PluginMenu);
              //item.addActionListener(ij);
    public static void main (String args[])
              JFMenu menapp = new JFMenu();
    public static void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description) {
         // Create instance of class ClassLinkList
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);
    // end main calling program
    class Hello extends Thread
    public int getNum()
    System.out.println("I can be ");
    return 5;
    public void rayshowName()
    System.out.println("anything i want ");
    public void rayshowName3()
    System.out.println("to be ");
    class Foo extends Thread
    public int getNum()
    System.out.println("IMHOFF");
    return 5;
    public void rayshowName()
    System.out.println("raYMOND");
    // FAMOUS PERSONS LINKED LIST EXAMPLE
    // Frans Coenen
    // Saturday 15 January 2000
    // Depaertment of Computer Science, University of Liverpool
    class ClassLinkList {
    /* FIELDS */
    public String className;
    public String shortcutName;
    public int methodNumber;
    public int yearOfDeath;
    public String occupation;
    public ClassLinkList next = null;
    public ClassLinkList linkRef5 = this;
    public ClassLinkList startRef = null;
    /* CONSTRUCTORS */
    /* FamousPerson constructor */
    public ClassLinkList(String classname, String shortcutname, int methodnumber, int year2,
                                  String description) {
         className = classname;
         shortcutName = shortcutname;
         methodNumber = methodnumber;
         yearOfDeath = year2;
         occupation = description;
         next = null;
    /* METHODS */
    /* Output famous person linked list */
    public void outputClassLinkedList()
         //public ClassLinkList outputClassLinkedList() {
         ClassLinkList linkRef = this;
         // Loop through linked list till end outputting each record in turn
    while (linkRef != null)
         //System.out.println(linkRef5);
         System.out.println(linkRef.className + ", " + linkRef.shortcutName +
                   " (" + linkRef.methodNumber + "-" + linkRef.methodNumber +
                   "): " + linkRef.occupation);
         linkRef = linkRef.next;     
    //return linkRef;
    //public String ShowCasname()
    //return String ;     
    /* Add a new record to the linked list */
    public ClassLinkList addRecordToLinkedList(ClassLinkList newRef) {
         ClassLinkList tempRef, linkRef;
         // Test if new person is to be added to start of list if so return
    if (newRef.testRecord(this) ) {
         newRef.next = this;
         return(newRef);
         // Loop through remainder of linked list
         tempRef = this;
         linkRef = this.next;
         while (linkRef != null) {
         if (newRef.testRecord(linkRef)) {
         tempRef.next = newRef;
              newRef.next = linkRef;
              return(this);
         tempRef = linkRef;
         linkRef = linkRef.next;
    // Add to end
    tempRef.next = newRef;
         return(this);
    /* Delete a record from the linked list given the first and last name. Four
    posibilities:
    1) Record to be deleted is at front of list
    2) Record to be deleted is at end of list
    3) Record to be deleted is in middle of list
    4) Record not found. */
    public ClassLinkList deleteRecord(String lName, String fName) {
    ClassLinkList tempRef, linkRef;
    // Record at start of list
    if ((this.className == lName) & (this.shortcutName == fName))
         return(this.next);
         // Loop through linked list to discover if record is in middle of list.
         tempRef = this;
    linkRef = this.next;
    while (linkRef != null) {
         if ((linkRef.className == lName) & (linkRef.shortcutName == fName)) {
    tempRef.next = linkRef.next;
    return(this);
    tempRef = linkRef;
    linkRef = linkRef.next;
    // Record at end of list, or not found
    if ((linkRef.className == lName) & (linkRef.shortcutName == fName))
                        linkRef = null;
         else System.out.println("Record: " + lName + " " + fName + " not found!");
         return(this);
    /* TEST METHODS */
    /* Test whether new record comes before existing record or not. If so return
    true, false otherwise. */
    private boolean testRecord(ClassLinkList existingRef) {
         int testResult = className.compareTo(existingRef.className);
         if (testResult < 0) return(true);
         else {
         if ((testResult == 0) & (shortcutName.compareTo(existingRef.shortcutName) < 0 ))
                             return(true);
         // Return false
         return(false);
         public void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description)
         // Create instance of class Famous Person
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);

    I have a similar problem. I am writing a program to read the class names from database and instantiate several classes which extends from ServiceThread (an abstract class extending from Thread).
    rs = pStmt.executeQuery();
    while(rs.next()) {
    String threadclassname = rs.getString("classname").trim();
    try{
    ServiceThread threadinstance = (ServiceThread)Class.forName(threadclassname).newInstance();
    }catch ...
    So far, only the first class is ever instantiated and runs fine. But subsequent classes do not even get pass the "... ... Class.forName(...).newInstance();" line.
    Funny thing is that there are also no exceptions. The JVM just seem to hang there.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Hi, problem occurs when I'm clicking a button or a new url on the current site. For instance, when i clicked that "Ask This" button on this web site, It redirects me to the default homepage. I cant go back and I'm losing the previous web site HELP PLEASE!

    Hi, problem occurs when I'm clicking a button or a new url on the current site. For instance, when i clicked that "Ask This" button on this web site, It redirects me to the default homepage. I cant go back and I'm losing the previous web site HELP PLEASE!

    Try the Firefox SafeMode. <br />
    ''A troubleshooting mode, which disables most Add-ons.'' <br />
    ''(If you're not using it, switch to the Default Theme.)''
    # You can open the Firefox 4.0 SafeMode by holding the '''Shft''' key when you use the Firefox desktop or Start menu shortcut.
    # Or use the Help menu item, click on '''Restart with Add-ons Disabled...''' while Firefox is running. <br />
    ''To exit the Firefox Safe Mode, just close Firefox and wait a few seconds before using the Firefox shortcut (without the Shft key) to open it again.''
    If it is good in the Firefox SafeMode, your problem is probably caused by an extension, and you need to figure out which one. <br />
    http://support.mozilla.com/en-US/kb/troubleshooting+extensions+and+themes

  • Establishing a Static IP help please :)

    In order to establish a static ip i need the DNS Server address, however, when it is the same as the Default Gateway address you have to either go to your router's web interface or call your internet provider to obtain your DNS Server address. I was wondering if it is even possible to establish a Static IP w/ your phone as your modem/router and if so how do i obtain my DNS server adress when their is no router web interface. thanks for the help
    Post relates to: Pre Plus p101vzw (Verizon)

    ElliottG wrote:
    and it just won't work. The internet will work, but I go check my ip, then go to restart my router, I do that, and reload the whatismyip page, my external ip changes...
    It is normal because you have dynamic IP address. Every router/modem restart will get you a different IP address. All machines on the internet will only "see" your external IP. Internal IP (192.168.1.whatever) will not be "seen" from the internet.
    When you go into control panel and go into internal protocol (tcp/ip) and set everything up, does the ip have to be outside the limits of the dhcp limit? Ex. 192.168.1.100 tp 192.168.1.49? I set it as 192.168.1.175 and it still doesn't work so I really need some help please...
    You are mixing private IP with real/internet IP addressing scheme. They are 2 different things.
    I'm probably guessing I need to get a static ip from my isp...but how come in all the guides it doesn't say that? and i'm sure my isp won't be too keen on giving me a static ip...
    For simplicity, I guess. Yes, you must spend extra money to get static IP.

  • My iphone 5 keeps on losing contact details and i am also having instances of old text messages being resent when I am actually sending newly written text messages help please?

    My iphone 5 keeps on losing contact details and i am also having instances of old text messages being resent when I am actually sending newly written text messages help please?

    My wife is having the same problems as a reciever. She works in a school as a teaching assistant and her teacher sends messages that are mixed with previous texts from ages ago.
    Can anyone shed some light on this problem or is it only her and this poster?
    2m42s

  • HELP PLEASE iPod Touch 4G went brown, then static, then turned off

    I was listening to music and looking at photos when my screen flashed brown, then then that static that comes up on a TV came on, then turned off. It isn't turning back on, last week when I connected it to a computer it made a noise, but it's been plugged in for the last 30 minutes and nothings come up on iTunes.
    I've tried holding the sleep and home button... IT DOESNT WORK.
    Help please!

    Try:
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iPod fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - If still not successful that indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar

  • Making an instance of a class using a String???Help!

    Hello,
    If have a problem.
    I have to make a method in which you put a string . This method must make an instance of a
    class, whose the name is specified in that String.
    How do I do that?

    private UrClass getAClass( String classname ) throws Exception
         return UrClass urass      = (UrClass)(Class.forName( classname ).newInstance();
    or
    private UrClass getAClass( String classname )
         try {
              return UrClass urass      = (UrClass)(Class.forName( classname ).newInstance();
         } catch ( Exception e ) {
              return null
    is it enough?
    [email protected]

  • I want to run single instance of my class ?

    i have a class with name Abc, i want when my Abc class is
    in running mode then i cant run my Abc class again untill my
    Abc class not exit.
    i want to do that in pure java, i have one logic but it is not
    proper salution.
    my logic is that when my programe is start first check a temprery file
    which is created by my programe and when i want to exit then i delete
    that temprery file.
    but if computer is shutdown unproperly and my programe is in running mode then my file is not delete.
    please any body give me help.
    i m thanksfull.
    Arif.

    Hi,
    let's make it more precise as so "if my class is in running mode" is not very precise - I guess, you are not talking of a class which has implemented the Runnable interface and is executed via "new Thread(Abc).start()". I think, you want a class, which can only have one instance of it at a time, right?
    It is no problem, to make a class, which has only one instance - it is called a Singleton class - it consists of the following:
    public class MySingleton extends Object // or any other class
    public static final instance = new MySingleton();
    //the trick here is to declare its constructor private
    private MySingleton() { super(); }
    // some other methods here
    }There is only one instance of this class accessible via MySingleton.instance. The problem with it is, that it doesn't match your requirements, as so you are not able to instantiate this class ever again, even so you would declare the "instance" field not final and set it to null.
    What you can do now is dealing with security managers - check the documentation of the newInstance() method of the Class class and the SecurityManager class, there you will find several links to documentation related with the use of an security manager.
    greetings Marsian
    P.S.: all these *** in the text are the letters a s s :(

  • Last Project -- Need Help, Please

    Okay, this is my last project, and I am struggling with it. The specification we were given was to write a program that reads in a file of dates and outputs the dates in descending order, using a priority queue. The PriorityQueue should implement the PriorityQueueInterface interface, and should implements a priority queue using a singly linked list. The list should be maintained in sorted order. This implementation should not use a heap.
    I have the code built, but when I run it is not reading my dates fully, and I get an error message. The LinkList is already built for us, but here is the rest of my code. First I input from my dates.txt:
    11/12/2000
    04/04/2004
    01/02/1998
    import java.io.*;
    public class DateDriver {
       public static void main(String[] args) throws IOException {
          PriorityQueue pq = new PriorityQueue();
          // ... read all Date objects from the file and enqueue them in the pq object
          BufferedReader in = new BufferedReader (new FileReader("C:/Users/April/Desktop/UMUC/CMIS241/Project4/Dates.txt"));
          Date date = new Date();
          date.input(in);
          while (!date.isNull()){
               pq.add(date);
               date = new Date();
               date.input(in);
               System.out.println(date);
          // ... dequeue the pq object and display the Date objects
          System.out.println("The dates in descending order are: ");
          while (!pq.isEmpty()){
               date = (Date) pq.dequeue();
               date.output(System.out);
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.PrintStream;
    public class Date implements InOutputable, Comparable {
       // ... define monthNames as a ?static final? array of String objects
       //  initialize the array with the first 3 characters of each month
         static final String[] monthNames = {null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
              "Oct", "Nov", "Dec"};
       // ... define the instance variables of class Date, i.e. day, month, year
         private String monthAbr, date;
         private int month, day, year;
       // ... define the default constructor (initializes the instance variables to zero)
         public Date(){
              this.date = "";
              month = 00;
              day = 00;
              year = 0000;
       // ... define the method toString
       //     This method should return the corresponding Date string in the following format: Nov, 11, 2006
         public String toString() {
               return (monthAbr + ", " + day + ", " + year);
       // ... define the methods specified by the interface InOutputable
    public boolean equals(InOutputable other) {
         Date otherDate = (Date) other;
         if (month == otherDate.month && day == otherDate.day && year == otherDate.year)
              return true;
         else
              return false;
    public void input(BufferedReader in) throws IOException {
         date = in.readLine();
         if (date == null)
              return;
         month = Integer.parseInt(date.substring(0, 2));
         day = Integer.parseInt(date.substring(3, 5));
         year = Integer.parseInt(date.substring(6, 10));
    public boolean isNull() {
         if (month == 0 && day == 0 && year == 0)
              return true;
         else
              return false;
    public void output(PrintStream writer) {
         writer.println(toString());
       // ... define the method specified by the interface Comparable
    public int compareTo(Object o) {
         Date otherDate = (Date) o;
         if(month == otherDate.month && day == otherDate.day && year == otherDate.year)
              return 0;
         else if (month >= otherDate.month && day >= otherDate.day && year >= otherDate.year)
              return 1;
         else
              return -1;
    public class PriorityQueue implements PriorityQueueInterface {   
       private RefSortedList lst = new RefSortedList();
       // ... define the methods specified by the interface PriorityQueueInterface
    public Comparable dequeue() throws EmptyQueue {
         return null;
    public void enqueue(Comparable key) throws FullQueue {
    public boolean isEmpty() {
         return false;
       // ... Use the lst object (by invoking list specific methods on it) when
       //     defining the PriorityQueueInterface methods.
       //     For example, method enqueue should be implemented by invoking list method add.
    public void add(Date date){
         lst.add(date);
    public void remove(Date date){
         lst.remove(date);
    }My output:
    Exception in thread "main" java.lang.NullPointerException
         at DateDriver.main(DateDriver.java:27)
    null, 4, 2004
    null, 2, 1998
    null, 0, 0
    The dates in descending order are:
    Can anybody please point me in the right direction? I know I am missing something, but I am unable to pinpoint it. I don't understand why the date.output(System.out) is throwing a null pointer exception. I am still working, but I thought maybe a fresh pair of eyes would help me.

    Dates implement Comparable... no need to sort them yourself
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    LinkedList<Date> dtes = new LinkedList<Date>();
    BufferedReader in = new BufferedReader (new FileReader("C:/dates.txt"));
    while (in.read()>0){
    dtes.add(sdf.parse(in.readLine()));
    }Edited by: wpp289 on Dec 11, 2008 1:27 PM

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Unsatisfied link when callind dll from run method Help Please?

    Hi,
    I get an unsatisfied link error while trying to calling a dll at a certain time period in a run method. The same dll works fine called in another setup and even called in a loop.
    Can anyone help please?
    import java.util.Timer;
    import java.util.TimerTask;
    * Schedule a task that executes once every second.
    public class TimeRetrieve {
        Timer timer;
        public TimeRetrieve() {
                 timer = new Timer();
            timer.schedule(new RemindTask(),
                        0,        //initial delay
                        1*1000);  //subsequent rate
        class RemindTask extends TimerTask
           String string_A;
           double d1;
         double d2;
         double d3;
         double d4;
         double d5;
         double d6;
         double d7;
         double d8;
         int numIter = 3;
         int start = 1;
            public void run()
                  if (numIter > 0) {
                  cinterface(start, string_A, d1, d2, d3, d4, d5, d6, d7, d8 );
              System.out.println("In Java action performed start button, after call to dll  \n");
              System.out.println("   string_A =  :" +string_A );
              System.out.println("doubles , \t  d1  \t d2  \t  d3  \t d4 \t d5 \t d6 \t d7 \t d8");
              System.out.println(d1 +"\t" +d2+"\t"+d3+"\t"+d4+"\t"+d5+"\t"+d6+"\t"+d7+"\t"+d8);
              numIter--;
                 } else
                 System.out.println("End Looping!");
                    System.exit
                 System.exit(0);  
        public static void main(String args[]) {
                   System.out.println("Starting Data Retrieval.");
                 new TimeRetrieve();
    // Load shared library which contains implementation of native methods
                    public native void cinterface(int start, String string_A, double d1, double d2, double d3, double d4,
                    double d5, double d6, double d7, double d8 );
                    static
                          try
                               System.out.println ("load cinterface"); //unsatisfied link
                               System.loadLibrary("cinterface");
                          catch (UnsatisfiedLinkError ee)
                               System.out.println
                                    ("Caught unsatisfied link error for dlls" );
                               System.out.println
                                    ("get local msg = " + ee.getLocalizedMessage() );
                               System.out.println ("getMessage " + ee.getMessage() );
                                   // System.out.println ("print Stack Trace " +ee.printStackTrace() );

    My mistake! I found it. Had some wrong names.

  • Little help please with forwarding traffic to proxy server!

    hi all, little help please with this error message
    i got this when i ran my code and requested only the home page of the google at my client side !!
    GET / HTTP/1.1
    Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
    Accept-Language: en-us
    UA-CPU: x86
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727)
    Host: www.google.com
    Connection: Keep-Alive
    Cookie: PREF=ID=a21457942a93fc67:TB=2:TM=1212883502:LM=1213187620:GM=1:S=H1BYeDQt9622ONKF
    HTTP/1.0 200 OK
    Cache-Control: private, max-age=0
    Date: Fri, 20 Jun 2008 22:43:15 GMT
    Expires: -1
    Content-Type: text/html; charset=UTF-8
    Content-Encoding: gzip
    Server: gws
    Content-Length: 2649
    X-Cache: MISS from linux-e6p8
    X-Cache-Lookup: MISS from linux-e6p8:3128
    Via: 1.0
    Connection: keep-alive
    GET /8SE/11?MI=32d919696b43409cb90ec369fe7aab75&LV=3.1.0.146&AG=T14050&IS=0000&TE=1&TV=tmen-us%7Cts20080620224324%7Crf0%7Csq38%7Cwi133526%7Ceuhttp%3A%2F%2Fwww.google.com%2F HTTP/1.1
    User-Agent: MSN_SL/3.1 Microsoft-Windows/5.1
    Host: g.ceipmsn.com
    HTTP/1.0 403 Forbidden
    Server: squid/2.6.STABLE5
    Date: Sat, 21 Jun 2008 01:46:26 GMT
    Content-Type: text/html
    Content-Length: 1066
    Expires: Sat, 21 Jun 2008 01:46:26 GMT
    X-Squid-Error: ERR_ACCESS_DENIED 0
    X-Cache: MISS from linux-e6p8
    X-Cache-Lookup: NONE from linux-e6p8:3128
    Via: 1.0
    Connection: close
    java.net.SocketException: Broken pipe // this is the error message
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
    at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
    at SimpleHttpHandler.run(Test77.java:61)
    at java.lang.Thread.run(Thread.java:595)
    at Test77.main(Test77.java:13)

    please could just tell me what is wrong with my code ! this is the last idea in my G.p and am havin difficulties with that cuz this is the first time dealin with java :( the purpose of my code to forward the http traffic from client to Squid server ( proxy server ) then forward the response from squid server to the clients !
    thanx a lot,
    this is my code :
    import java.io.*;
    import java.net.*;
    public class Test7 {
    public static void main(String[] args) {
    try {
    ServerSocket serverSocket = new ServerSocket(1416);
    while(true){
    System.out.println("Waiting for request");
    Socket socket = serverSocket.accept();
    new Thread(new SimpleHttpHandler(socket)).run();
    socket.close();
    catch (Exception e) {
    e.printStackTrace();
    class SimpleHttpHandler implements Runnable{
    private final static String CLRF = "\r\n";
    private Socket client;
    private DataOutputStream writer;
    private DataOutputStream writer2;
    private BufferedReader reader;
    private BufferedReader reader2;
    public SimpleHttpHandler(Socket client){
    this.client = client;
    public void run(){
    try{
    this.reader = new BufferedReader(
    new InputStreamReader(
    this.client.getInputStream()
    InetAddress ipp=InetAddress.getByName("192.168.6.29"); \\ my squid server
    System.out.println(ipp);
    StringBuffer buffer = new StringBuffer();
    Socket ss=new Socket(ipp,3128);
    this.writer= new DataOutputStream(ss.getOutputStream());
    writer.writeBytes(this.read());
    this.reader2 = new BufferedReader(
    new InputStreamReader(
    ss.getInputStream()
    this.writer2= new DataOutputStream(this.client.getOutputStream());
    writer2.writeBytes(this.read2());
    this.writer2.close();
    this.writer.close();
    this.reader.close();
    this.reader2.close();
    this.client.close();
    catch(Exception e){
    e.printStackTrace();
    private String read() throws IOException{
    String in = "";
    StringBuffer buffer = new StringBuffer();
    while(!(in = this.reader.readLine()).trim().equals("")){
    buffer.append(in + "\n");
    buffer.append(in + "\n");
    System.out.println(buffer.toString());
    return buffer.toString();
    private String read2() throws IOException{
    String in = "";
    StringBuffer buffer = new StringBuffer();
    while(!(in = this.reader2.readLine()).trim().equals("")){
    buffer.append(in + "\n");
    System.out.println(buffer.toString());
    return buffer.toString();
    Edited by: Tareq85 on Jun 20, 2008 5:22 PM

  • Need help in compare method of Comparator class

    I am writing a program that will display elements of a TreeMap in an order in which I want. By default the order is ascending. To change the order I need to override the compare method of the Comparator class.
    I've done this in my code below.
    I want to display keys with lower-case 1st and then those with upper-case.
    Please help.
    import java.util.*;
    public class MyComparator implements Comparator {
      public int compare(Object o1, Object o2) {
        String s1 = o1.toString();
        String s2 = o2.toString();
        return s1.compareTo(s2);
      public static void main(String[] args) {
        Map names = new TreeMap(new MyComparator());
        names.put("a", new Integer(1435)); 
        names.put("b", new Integer(1110));
        names.put("A", new Integer(1425));
        names.put("B", new Integer(987));
        names.put("C", new Integer(1323));   
        Set namesSet = names.keySet();
        Iterator iter = namesSet.iterator();
        while(iter.hasNext()) {
          String who = (String)iter.next();
          System.out.println(who + " => " +     names.get(who));
    }

    public int compare(Object o1, Object o2) {
        String s1 = o1.toString();
        String s2 = o2.toString();
        String ss1 = beginsWithLowerLetter(s1)? s1.toUpperCase() : s1.toLowerCase();
        String ss2 = beginsWithLowerLetter(s2)? s2.toUpperCase() : s2.toLowerCase();
        return ss1.compareTo(ss2);
    }

Maybe you are looking for

  • Library Projects compiled using Flash Builder and ANT have different outputs

    Hi Guys., I am really having hard time to get something work right with RSL projects in Flex 3.2 SDK. Here is my weird problem. I have a library projects which has the following settings in Flash Builder Link Type : External airglobal.swc framework.s

  • E-Sourcing reports

    Hi, How to design Reports in E-Sourcing? Where to create this report in E-Sourcing? Please explain ... Thanks.. Naresh

  • Class not found: DirectLogic

    I am trying to open an *.lks file developed with 4.0.1 in Lookout version 5.0 and I am getting the following errors from the Compiler. C:\Program Files\National Instruments\Lookout 5.0\thomaswtp010811.lks C:\Program Files\National Instruments\Lookout

  • Okay, so I have a slide show with music - how to upload with Music to .mac

    First, I clicked share and it showed only one image at .mac, but I want to do the whole event plus the music. Any ideas? Thanks Or do I need to use iDVD?

  • The dialer in lumia 800 is missing key critical fe...

    I have had my Lumia800 for about 5 months now, and I am not happy. Previously I have owned both Iphones and android phones, and WP7.5 - or Lumia800 - is way way behind these phones on even very simple features. I could mention a whole list of key fea