Skip to main content

how to synchronize order by subclass in Java

1 reply [Last post]
hao5ang
Offline
Joined: 2012-04-11
Points: 0

The base class :

public abstract class Base(){
public abstract String doTask();
}

The child classes :
public class Child1() extends Base{
public String doTask(){};
}

public class Child2() extends Base{
public String doTask(){};
}

I want let only one thread really run child1's doTask method . If the second thread find there have already a thread running the doTask method , the second one will return directly . The same will happen on class child2 .
I try to implement that by the code below :

public class Child1() extends Base{
public static Boolean running = false;

    public String doTask(long arg0) throws Exception {
        synchronized (running) {
            if (running == true) {
                return "There is a task is still running , current task is ignored .";
            }
            running = true;
        }
        try {
            String result = doMyTask();
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            synchronized (running) {
                running = false;
            }
        }
    }
}

But I think it's not really good . Because every child class will need this same code . I want to move the code to the Base class . But if I move the code to father class , there will only one child class can run the task . Actually I want one child1 task and one child2 task can both run normally .
I really want Java can support abstract field and then I can synchronize the field in child class ^_^
Can someone to give me a good method to solve this problem ?
Any response is appreciatory .

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
hao5ang
Offline
Joined: 2012-04-11
Points: 0

Can anyone help me ?