0

I'm getting an IllegalMonitorStateException in my code.

Inside startEmployeeProcess() method I start a thread1 (EmployeeThread) and inside the switch I call thread1.wait() (case 3)

What is the problem in my code?

Plz Help

Thanks

public class EmployeeManager {

private ArrayList<Employee> employees = new ArrayList<Employee>();
Scanner sc = null;

private  synchronized void startEmployeeProcess(EmployeeManager employeemanager)  {
    System.out
            .println("********************THREAD OBJECT CREATION PROCESS STARTED**************************");
    EmployeeThread employethread = new EmployeeThread(employees);
    Thread thread1 = new Thread(employethread);
    System.out
            .println("********************GOING TO START THE FILE WRITER THREAD******************************");
    thread1.start();
    Scanner sc = new Scanner(System.in);
    do {
        System.out.println("Choose any one option");
        System.out.println("1.Create Employee");
        System.out.println("2.Search Employee by id");
        System.out.println("3.delete Employee by id ");
        System.out.println("4.Print all employee Employee details");
        int choice = sc.nextInt();
        switch (choice) {
        case 1:
            employeemanager.createEmployee();
            break;
        case 2:
            System.out.println("Enter Empid");
            int empId = sc.nextInt();
            employeemanager.searchEmployee(empId);
            break;
        case 3:



                System.out.println("Enter EmpId ");
                try {
                    System.out.println("*************************FILE WRITER THREAD IS IN WAIT PROCESS**********************");
                    thread1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("***************Deleting*****************");
                int EmpId = sc.nextInt();
                synchronized(employees)
                {
                boolean isEmployeeDeleted = employeemanager.deleteEmployee(EmpId);
                if (isEmployeeDeleted) {
                    System.out.println("Employee is deleted ....!");
                } else {
                    System.out.println("Employee not found");
                }
                System.out.println("*************************FILE WRITER THREAD IS NOTIFIED**********************");
                thread1.notify();
                }
                break;


        case 4:

            employeemanager.printAllEmployeeDetails();

        default:
            System.out.println("wrong choice plz try again....");
            break;

        }
    } while (true);
}

public static void main(String[] args) 
{
    EmployeeManager employeemanager = new EmployeeManager();
    employeemanager.startEmployeeProcess(employeemanager);

}

public void createEmployee() {
    Employee employee = new Employee();
    sc = new Scanner(System.in);
    System.out.println("Enter Employee Name");
    String empName = sc.next();
    System.out.println("Enter employee Id");
    int empId = sc.nextInt();
    System.out.println("Enter employee worklocation");
    String empWorkLocation = sc.next();
    System.out.println("Enter employee Mobile Number");
    int mobNo = sc.nextInt();
    System.out.println("Enter Employee Address");
    String empAddress = sc.next();
    System.out.println("Enter Employee Age");
    int empAge = sc.nextInt();
    employee.setEmpName(empName);
    employee.setEmpId(empId);
    employee.setEmpWorkingLocation(empWorkLocation);
    employee.setEmpMobileNo(mobNo);
    employee.setEmpAddress(empAddress);
    employee.setEmpAge(empAge);
    employees.add(employee);
    System.out.println("employee created ....!");
}

public void searchEmployee(int empId) {
    Iterator<Employee> iterator = employees.iterator();
    while (iterator.hasNext()) {
        Employee employee = (Employee) iterator.next();
        int empid = employee.getEmpId();
        if (empId == empid) {
            System.out.println(employee);
        } else {
            System.out.println("Employee not found");

        }
    }

}

public boolean deleteEmployee(int EmpId) {
    Iterator<Employee> iterator = employees.iterator();
    while (iterator.hasNext()) {
        Employee employee = (Employee) iterator.next();
        int empid = employee.getEmpId();
        if (EmpId == empid) {
            iterator.remove();
            return true;

        }

    }
    return false;
}

public void printAllEmployeeDetails() {
    System.out.println("all employee deatils are ...");
    System.out.println(employees);

}

}

Class:

EmployeeThread

public class EmployeeThread implements Runnable {
private ArrayList<Employee> employees;

public EmployeeThread(ArrayList<Employee> employees) {
    this.employees = employees;
}

public  void run() {
    try {
        synchronized(employees)
        {

            String filename = "employee.txt";
            FileWriter filewriter = new FileWriter(filename);
            BufferedWriter bufferedwriter = new BufferedWriter(filewriter);
            while (true) {
                for (Employee employee : employees)
                {
                    if (employee.getReadStatus().equalsIgnoreCase("R"))

                    {
                        bufferedwriter.write(employee.toString());
                        employee.setReadStatus("W");
                    }
                }
                employees.wait();
                employees.notify();
            }
            }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }

}
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
user101
  • 11
  • 2
  • Maybe the answer of this question helps http://stackoverflow.com/questions/13335367/why-does-this-code-result-in-illegalmonitorstate-exception You need to invoke wait() inside the synchronized block. – RubioRic Apr 22 '16 at 05:18
  • thanks but still getting same exception.. – user101 Apr 22 '16 at 05:22
  • It almost never makes sense to `wait()` on a thread. It almost certainly doesn't do what you think it does. Perhaps you intended to use `join()` – Peter Lawrey Apr 22 '16 at 06:06

1 Answers1

1

Mistake is obvious:

thread1.wait();
thread1.notify();

Please remember, you must invoke the object's wait() or notify() in the same object's synchronized block, that says you must get the object's monitor lock before invoke wait() or notify(), like:

synchronized(obj1){
    // obj1.wait();  
    // or obj1.notify();
}

I think you should understand java synchronized keyword clearly, you can see this tutorial.

Hope to help you.

haolin
  • 216
  • 1
  • 5
  • thanks buddy,,, could you give the correct whole code of this.. – user101 Apr 22 '16 at 05:31
  • I feel your logic is a little confused, you needn't `thread1.wait()` when **delete the employee**. and I think it isn't necessary to use thread to write **employees** to file. You only wrap a method writes employees to file, invoke it when **create** or **delete** an employee to refresh newest **employees** to file. And I suggest you use **Set** instead of **List** – haolin Apr 22 '16 at 06:03
  • Thanks for the good suggestion – user101 Apr 22 '16 at 06:13