找出一个物体的空闲时间

时间:2015-01-18 06:36:08

标签: java

我需要计算一个对象的空闲时间让我说我有一个pojo,其中一个对象是在下面显示的其他类中创建的,并且在该类中我创建了该对象但是没有使用它但后来有些我怎么样决定知道该对象的空闲时间,请告知我如何计算该对象的空闲时间..

让我们说下面是我的pojo

public class Emp implements Comparable {

    String name, job;
    int salary;

    public Emp(String n, String j, int s) {
        this.name = n;
        this.job = j;
        this.salary = s;

    }

    public int hashcode() {
        return name.hashCode() + job.hashCode() + salary;
    }

    public boolean equals(Object o) {

        Emp e1 = (Emp) o;
        return this.name.equals(e1.name) && this.job.equals(e1.job) && this.salary == e1.salary;
    }


    // method have return type
    public int compareTo(Object o) {
        Emp e1 = (Emp) o;
        return this.name.compareTo(e1.name);//compareToIgnoreCase
    }




    public void display()
    {
      System.out.println(name+"\t"+job+"\t"+salary);
     }

}

现在可以说还有另一个班级

class Abc 
{

public static void main(String args[])
{

Emp e1 = new Emp();//created e1 object but not use it later on decided to find out its idle time

}
}

1 个答案:

答案 0 :(得分:2)

不使用分析工具,在对象的构造函数中记录对象创建时间,并跟踪方法'执行时间(例如,通过将全局执行计时器保持在对象内并在每次方法完成时聚合执行时间)。

然后,对象的空闲时间是(当前时间 - 对象的创建时间 - 所有方法的总执行时间)。例如:

import java.util.concurrent.atomic.AtomicLong;

public class Emp implements Comparable {

    String name, job;
    int salary;
    private AtomicLong busyTime;
    private long instantiationTime;

    public Emp(String n, String j, int s) {
        instantiationTime = System.nanoTime();
        this.name = n;
        this.job = j;
        this.salary = s;
    }

    public int hashcode() {
        long startTime = System.nanoTime();
        int returnValue = name.hashCode() + job.hashCode() + salary;
        busyTime.addAndGet(System.nanoTime() - startTime);
        return returnValue;
    }

    public boolean equals(Object o) {
        long startTime = System.nanoTime();
        Emp e1 = (Emp) o;
        boolean returnValue = this.name.equals(e1.name)
                && this.job.equals(e1.job) && this.salary == e1.salary;
        busyTime.addAndGet(System.nanoTime() - startTime);
        return returnValue;
    }

    // method have return type
    public int compareTo(Object o) {
        long startTime = System.nanoTime();
        Emp e1 = (Emp) o;
        int returnValue = this.name.compareTo(e1.name);
        busyTime.addAndGet(System.nanoTime() - startTime);
        return returnValue;// compareToIgnoreCase
    }

    public void display() {
        long startTime = System.nanoTime();
        System.out.println(name + "\t" + job + "\t" + salary);
        busyTime.addAndGet(System.nanoTime() - startTime);
    }

    public long getIdleTime() {
        return System.nanoTime() - instantiationTime - busyTime.get();
    }
}