2

Suppose I have a class like this:

package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;

public class RecordLogging implements LittleLogging{

    private LinkedList <String> logs;
    private boolean startNew;

    public RecordLogging() {
        logs = new LinkedList<String>();
    }

    public void log(String log) {
        logHelper(log);
        startNew = true;
    }

    public void logPart(String log) {
        logHelper(log);
        startNew = false;
    }

    private void logHelper(String log){
        // DO STUFF
    }

    public LinkedList<String> getResults() {
        return logs;
    }

}

Now suppose that I need a thread safe version of this code. I need the tread safe version to implement LittleLogging. I want the thread safe copy to have the same behavior as this class except I would like it to be thread safe. Is it safe to do this:

package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;

public class SyncRecordLogging extends RecordLogging {

    public SyncRecordLoging() {
        super();
    }

    public syncronized void log(String log) {
        super.log(log);
    }

    public syncronized void logPart(String log) {
        super.log(log);
    }

    public syncronized LinkedList<String> getResults() {
        return logs;
    }
}

Bonus Question: Where should I look for documentation about syncronization and threading

1
  • 1
    You know, not everything needs to use inheritance. Try a little composition from time to time to mix things up. ;) Commented Aug 8, 2011 at 19:53

1 Answer 1

3

You can use composition instead. Also note that getResults creates a copy of the list:

public class SyncRecordLogging  implements LittleLogging{

    private final RecordLogging _log;

    public SyncRecordLogging() {
        _log = new RecordLogging();
    }

    public synchronized void log(String log) {
        _log.log(log);
    }

    public synchronized void logPart(String log) {
        _log.logPart(log);
    }

    public synchronized LinkedList<String> getResults() {
        // returning copy to avoid 'leaking' the enderlying reference
        return new LinkedList(_log.getResults());
    }
}

Best read: Java Concurrency In Practice

Sign up to request clarification or add additional context in comments.

2 Comments

I think that I would not need to include logHelper for this case.
@sixtyfootersdude: Correct, removed from answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.