Hosseini
Hosseini

Reputation: 557

convert mutable variable to immutable in java with less pain

sometime i have no choice to use mutable variable instead of immutable variables i know how many ways can create immutable vars but i wonder this way also correct its really convert mutable to immutable and i dont use concurrency or multithreading in my code just Curious?

public class Config implements FindIt {
....
    private final class DateHolder{

    private final Date dateContainDateObject;

    DateHolder(String date) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        dateContainDateObject = dateFormat.parse(date);
    }

    public Date getDate(){
        return dateContainDateObject;
    }

   }
}

this is nested class and i use it like

private DateHolder holder;

and fill the holder variable in Config constructor class so holder variable are ThreadSafe ?

Upvotes: 1

Views: 816

Answers (2)

nader hamidi
nader hamidi

Reputation: 11

can say is safe when you make class private and non-static, when you create form Config class you have only one DateHolder .

http://www.javapractices.com/topic/TopicAction.do?Id=29

why is static inner class singleton thread safe

http://www.javatpoint.com/how-to-create-immutable-class

Upvotes: 1

Nathan Hughes
Nathan Hughes

Reputation: 96385

Date is a mutable object. Making it final means you can't change the reference to it, but you can still change what's at the reference (java.util.Date/Calendar nastiness strikes again, switch to the Java 8/Joda Time way if you can).

Don't expose any references to the Date member to the outside world. Instead make a defensive copy and pass that back instead. You might consider saving the time value as a final long instance member and only instantiating a Date when you need it.

Upvotes: 2

Related Questions