简体   繁体   中英

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM