Deserialization of a singleton object - java

Hi i'm trying to find a way to serialize and deserialize a singleton object while retrieving the object that was serialized before e.g: after I want to add doctors to my hospital object and after it being deserialized i get my doctors list back.
I read that in order to serialize a singleton I need to add readResolve() method.
but still every time i rebuild my object I'm getting new instance and it's empty, although i'm not getting any errors
public class Hospital implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static Hospital theHospital = null;
private HashMap<Integer, Doctor> doctors;
private HashMap<Integer, Nurse> nurses;
private HashMap<Integer, PatientReport> reports;
private HashMap<Integer, Patient> patients;
private HashMap<Integer, Patient> hotelPatients;
private HashMap<Integer, Disease> diseases;
private HashMap<Integer, Department> departments;
private HashMap<String,Department> departmentsByName;
private HashMap<Patient, HashSet<Doctor>> doctorsList;
private HashMap<Patient, HashSet<Nurse>> nursesList;
private TreeMap<Integer, Nurse> nurseShiftSet;
private ArrayList<SubDepartment> subSet;
private HashMap<String,HashMap<String,Doctor>> docUser;
private HashMap<String,HashMap<String,Nurse>> nurseUser;
private TreeSet<Department> DepList;
public static Hospital getInstance() {
if (theHospital == null){
theHospital = new Hospital();
}
return theHospital;
}
this is the object getInstance()
and here is the methods that i have used to write and read the serialized file .
private static ObjectInputStream input;
public static void writeObject(Hospital h) {
try {
FileOutputStream file = new FileOutputStream("Hospital.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(h);
out.close();
file.close();
} catch (IOException e) {
System.out.println("Error in creating the file");
}
}
public static Hospital readObject() {
try {
FileInputStream file = new FileInputStream("Hospital.ser");
input = new ObjectInputStream(file);
Hospital h = (Hospital) input.readObject();
file.close();
input.close();
return h;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Update
Example :
Hospital h = Hospital.getInstance();
Department department = new Department("department name");
HashMap<String,Department> map = h.getDepartmentsByName();
// adding the department to the hospital instance .
map.put(department.getName(),department);
Serializing.writeObject(h); // writing the given instance h.
map.remove(d.getName());
// removing from the current instance after serializing.
h = Serializing.readObject(); // deserializing from the file.
map = h.getDepartmentsByName();
map.get(d.getName);// i'm expecting to return the department d , but it returns null.

Use object-mappers. Also your question doesn’t explain what exactly you are looking for. Share some examples of the same to explain the problem. Also, serialize and deserialise doesn’t seem right the way you are doing.

Related

relate toString with object creation

I have a fairly basic Java class with some class variables. I have overwridden toString() to provide me with a string output (which will eventually be output to a text file).
I am trying to elegantly create a way for me to use this string output to recreate the object with all of the variables set as before. The class looks something like this:
public class Report {
private String itemA;
private String itemB;
private String itemC;
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Items are::");
sb.append("\nItem A is: ").append(itemA);
sb.append("\nItem B is: ").append(itemB);
sb.append("\nItem C is: ").append(itemC);
return sb.toString();
}
}
this is how I can potentially tackle it using reflection:
public class Report {
private String itemA;
private String itemB;
private String itemC;
private final Map<String, String> MAPPING = new HashMap<>();
public Report(String itemA, String itemB, String itemC) {
this.itemA = itemA;
this.itemB = itemB;
this.itemC = itemC;
MAPPING.put("Item A is: ", "itemA");
MAPPING.put("Item B is: ", "itemB");
MAPPING.put("Item C is: ", "itemC");
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Items are::");
MAPPING.entrySet().forEach(entry -> {
sb.append("\n").append(entry.getKey()).append(BeanUtils.getProperty(this, entry.getValue()));
});
return sb.toString();
}
public Report createReportFromString(String reportString) {
List<String> reportLines = Arrays.asList(reportString.split("\n"));
HashMap<String, String> stringObjectRelationship = new HashMap<>();
reportLines.forEach(reportLine -> {
Optional<String> matchingKey = MAPPING.keySet().stream().filter(reportLine::contains).findFirst();
matchingKey.ifPresent(key -> {stringObjectRelationship.put(MAPPING.get(key), reportLine.split(key)[1]);});
});
stringObjectRelationship.forEach((variableName, variableValue) -> BeanUtils.setProperty(this, variableName, variableValue));
return this;
}
}
I basically want to relate the key in the report ("Item A is: ") to the name of the corresponding variable ("itemA") and use this relationship in both the toString() method and the createReportFromString(String string) method. Now when doing this there are a lot of possible exceptions that can be thrown and need to either be handled or thrown - and it then looks a lot less elegant than I would like.
I don't know if this is possible to do without reflection - or perhaps I could rearrange this class to make this possible?
What I can`t change is the structure of the string output in the toString().
Reflection bears multiple features:
Automatic discovery of features of a program at runtime
Support for dealing with features unknown at compile-time
Provide an abstraction of program features (e.g. methods or fields)
Your approach suggests that you don’t want an automatic discovery, as you are specifying the three elements explicitly. This is a good thing, as it makes your program more robust regarding future changes, as dealing with automatically discovered, potentially unknown program elements will destroy any help from the compiler, as it can’t tell you when there are mismatches.
You only want the third point, an abstraction over the elements of your report. You can create such an abstraction yourself, tailored to your use case, without Reflection, which will be more robust and even more efficient:
public class Report {
static final class Element {
final String header;
final Function<Report,String> getter;
final BiConsumer<Report,String> setter;
final Pattern pattern;
Element(String header,
Function<Report, String> getter, BiConsumer<Report, String> setter) {
this.header = header;
this.getter = getter;
this.setter = setter;
pattern = Pattern.compile("^\\Q"+header+"\\E(.*?)$", Pattern.MULTILINE);
}
}
static final List<Element> ELEMENTS = List.of(
new Element("Item A is: ", Report::getItemA, Report::setItemA),
new Element("Item B is: ", Report::getItemB, Report::setItemB),
new Element("Item C is: ", Report::getItemC, Report::setItemC));
private String itemA, itemB, itemC;
public Report(String itemA, String itemB, String itemC) {
this.itemA = itemA;
this.itemB = itemB;
this.itemC = itemC;
}
#Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Items are:");
ELEMENTS.forEach(e ->
sb.append('\n').append(e.header).append(e.getter.apply(this)));
return sb.toString();
}
public static Report createReportFromString(String reportString) {
return new Report("", "", "").setValuesFromString(reportString);
}
public Report setValuesFromString(String reportString) {
Matcher m = null;
for(Element e: ELEMENTS) {
if(m == null) m = e.pattern.matcher(reportString);
else m.usePattern(e.pattern).reset();
if(!m.find())
throw new IllegalArgumentException("missing \""+e.header+'"');
e.setter.accept(this, m.group(1));
}
return this;
}
public String getItemA() {
return itemA;
}
public void setItemA(String itemA) {
this.itemA = itemA;
}
public String getItemB() {
return itemB;
}
public void setItemB(String itemB) {
this.itemB = itemB;
}
public String getItemC() {
return itemC;
}
public void setItemC(String itemC) {
this.itemC = itemC;
}
}
This works with Java’s out-of-the-box features, not requiring another library to simplify the operation.
Note that I changed the code pattern, as createReportFromString is a misleading name for a method modifying an already existing object. I used the name for a factory method truly creating a new object and added a another method for setting the values of the object (as a direct counter-part to toString).
If you are still using Java 8, you can replace List.of(…) with Arrays.asList(…) or better Collections.unmodifiableList(Arrays.asList(…)).
You can also remove the .reset() call in the setValuesFromString method. When you remove it, the elements in the input string are required to be in the same order as the toString() method produces. This makes it a bit less flexible, but also more efficient if you expand the code to have a lot more elements.
#JimboMcHiggins assuming I can change the toString output how exactly would you tie together serialization and deserialization with some common mapping?
I would leave the toString unchanged and move the responsibility of serialization to java.io.Serializable. Correct me if this is not an acceptable approach. The mapping would be defined by the class fields of your Report pojo. This would also allow you to change your toString without breaking deserialization of existing objects.
import java.io.Serializable;
public class Report implements Serializable {
private static final long serialVersionUID = 1L;
private String itemA;
private String itemB;
private String itemC;
public Report(String itemA, String itemB, String itemC) {
this.itemA = itemA;
this.itemB = itemB;
this.itemC = itemC;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Items are::");
sb.append("\nItem A is: ").append(itemA);
sb.append("\nItem B is: ").append(itemB);
sb.append("\nItem C is: ").append(itemC);
return sb.toString();
}
}
Example Usage
public class Test1 {
public static void main(String[] args) {
Report report = new Report("W", "O", "W");
System.out.println(report);
String filename = "file.ser";
// Serialization
try
{
//Saving of report in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of report
out.writeObject(report);
out.close();
file.close();
System.out.println("Report has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Report report1 = null;
// Deserialization
try
{
// Reading the report from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of report
report1 = (Report)in.readObject();
in.close();
file.close();
System.out.println("Report has been deserialized ");
System.out.println(report1);
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output
Items are::
Item A is: W
Item B is: O
Item C is: W
Report has been serialized
Report has been deserialized
Items are::
Item A is: W
Item B is: O
Item C is: W

Serialize object that contains a Dataset

I am using Spark 2.3.1 with Java
I have an object that encapsulate a Dataset. I want to be able to serialize and deserialize this object.
My code is as follow :
public class MyClass implements Serializable {
private static final long serialVersionUID = -189012460301698744L;
public Dataset<Row> dataset;
public MyClass(final Dataset<Row> dataset) {
this.dataset = dataset;
}
/**
* Save the current instance of MyClass into a file as a serialized object.
*/
public void save(final String filepath, final String filename) throws Exception{
File file = new File(filepath);
file.mkdirs();
file = new File(filepath+"/"+filename);
try (final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(this);
}
}
/**
* Create a new MyClass from a serialized MyClass object
*/
public static MyClass load(final String filepath) throws Exception{
final File file = new File(filepath);
final MyClass myclass;
try (final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
myclass = ((MyClass) ois.readObject());
}
System.out.println("test 1 : "+ myclass);
System.out.println("test 2 : "+ myclass.dataset);
myclass.dataset.printSchema();
return myclass;
}
// Some other functions
}
But the serialization does not seem to be done properly. The load() function give me the following display :
test 1 : MyClass#520e6089
test 2 : Invalid tree; null:
null
And throws a java.lang.NullPointerException on the printSchema()
What am I missing to properly serialize my object ?
Spark Datasets are meaningful only in the scope of the session that has been used to create these. Therefore serializing Dataset is utterly meaningless.
If you want to serialize data just write Dataset to a persistent storage.
If you want to "serialize" pipeline, just keep use the code (method) that takes some form of input, and returns desired Dataset. Don't try to serialize Dataset itself.

Unable to Serialize Hashmap ,java.io.NotSerializableException

public class Common implements Serializable{
private static HashMap<Integer,List<LevelList>> levelListMap = new HashMap<>();
public static Map<Integer, List<LevelList>> getLevelListMap(Context context) {
File file = new File(context.getDir("data", MODE_PRIVATE), "map");
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream(file));
levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return levelListMap;
} ...
}
I am unable to serialize hashmap.I keep getting java.io.NotSerializableException for
levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();
public class LevelList implements Serializable{
public int id;
public String title;
public String imgurl;
public String songurl;
public String songtext;
boolean isFavourite;
public void release() {
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
public boolean isFavourite(){
return isFavourite;
}
}
HashMap is serializable, but the keys and values must also be serializable. Make sure that all keys and values are serializable, and that their fields are also serializable (excluding transient and static members).
Edit:
HashMap<Integer,List<LevelList>>, is your List implementation serializable?
Check this link How to serialize a list in Java. Standard implementation of List, i.e. ArrayList, LinkedList, etc. are serializable.
If you declare your List as one of the List subtypes such as ArrayList<LevelList> levelList = new ArrayList<LevelList>(); then it should be serializable out of the box. Otherwise you will need to cast in a safe way, such as setting the List implementation with <T extends List<Foo> & Serializable> setFooList(T list) as suggested by Theodore Murdock in that answer thread.

Implementing an equivalent to String.intern() for other objects

I'm trying to implement an equivalent to String.intern(), but for other objets.
My goal is the following:
I've an object A which I will serialize and then deserialize.
If there is another reference to A somewhere, I want the result of the deserialization to be the same reference.
Here is one example of what I would expect.
MyObject A = new MyObject();
A.data1 = 1;
A.data2 = 2;
byte[] serialized = serialize(A);
A.data1 = 3;
MyObject B = deserialize(serialized); // B!=A and B.data1=1, B.data2=2
MyObject C = B.intern(); // Here we should have C == A. Consequently C.data1=3 AND C.data2=2
Here is my implementation atm. (the MyObject class extends InternableObject)
public abstract class InternableObject {
private static final AtomicLong maxObjectId = new AtomicLong();
private static final Map<Long, InternableObject> dataMap = new ConcurrentHashMap<>();
private final long objectId;
public InternableObject() {
this.objectId = maxObjectId.incrementAndGet();
dataMap.put(this.objectId, this);
}
#Override
protected void finalize() throws Throwable {
super.finalize();
dataMap.remove(this.objectId);
}
public final InternableObject intern() {
return intern(this);
}
public static InternableObject intern(InternableObject o) {
InternableObject r = dataMap.get(o.objectId);
if (r == null) {
throw new IllegalStateException();
} else {
return r;
}
}
}
My unit test (which fails):
private static class MyData extends InternableObject implements Serializable {
public int data;
public MyData(int data) {
this.data = data;
}
}
#Test
public void testIntern() throws Exception {
MyData data1 = new MyData(7);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(data1);
oos.flush();
baos.flush();
oos.close();
baos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
MyData data2 = (MyData) ois.readObject();
Assert.assertTrue(data1 == data2.intern()); // Fails here
}
The failure is due to the fact that, when deserializing, the constructor of InternableObject is called, and thus objectId will be 2 (even if the serialized data contains "1")
Any idea about how to solve this particular problem or, another approach to handle the high level problem ?
Thanks guys
Do not use the constructor to create instances. Use a factory method that checks if an instance already exists first, only create an instance if there isn't already a matching one.
To get serialization to cooperate, your class will need to make use of readResolve() / writeReplace(). http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html#4539
The way you implemented your constructor, you're leaking a reference during construction, which can lead to very hard to nail down problems. Also, your instance map isn't protected by any locks, so its not thread save.
Typically intern() forms an aspect, and maybe should not be realized as a base class, maybe too restricting its usage in a more complex constellation.
There are two aspects:
1. Sharing the "same" object.
Internalizing an object only gives a profit, when several objects can be "internalized" to the same object. So I think, that InternalableObjecte. with a new sequential number is not really adequate. More important is that the class defines a fitting equals and hashCode.
Then you can do an identity Map<Object, Object>:
public class InternMap {
private final Map<Object, Object> identityMap = new HashMap<>();
public static <I extends Internalizable<?>> Object intern(I x) {
Object first = identityMap.get(x);
if (first == null) {
first = x;
identityMap.put(x, x);
}
return first;
}
}
InternMap could be used for any class, but above we restrict it to Internalizable things.
2. Replacing a dynamically created non-shared object with it's .intern().
Which in Java 8 could be realised with a defualt method in an interface:
interface Internalizable<T> {
public static final InternMap interns = new InternMap();
public default T intern(Class<T> klazz) {
return klazz.cast(internMap.intern(this));
}
class C implements Internalizable<C> { ... }
C x = new C();
x = x.intern(C.class);
The Class<T> parameter needed because of type erasure. Concurrency disregarded here.
Prior to Java 8, just use an empty interface Internalizable as _marker: interface, and use a static InternMap.

Java: accessing transient object fields inside class

Accessing private transient object fields from any method in class must be controlled with some code. What is the best practice?
private transient MyClass object = null;
internal get method:
private MyClass getObject() {
if (object == null)
object = new MyClass();
return object;
}
// use...
getObject().someWhat();
or "make sure" method:
private void checkObject() {
if (object == null)
object = new MyClass();
}
// use...
checkObject();
object.someWhat();
or something clever, more safe or more powerful?
Transient fields are lost at serialization but you need them only after deserialization, so you have to restore them to what you need in the readObject method...
Have to post a new answer about transient because it's too long for a comment. Following code prints
Before: HELLO FOO BAR
After: HELLO null null
public class Test {
public static void main(String[] args) throws Exception {
final Foo foo1 = new Foo();
System.out.println("Before:\t" + foo1.getValue1() + "\t" + foo1.getValue2() + "\t" + foo1.getValue3());
final File tempFile = File.createTempFile("test", null);
// to arrange for a file created by this method to be deleted automatically
tempFile.deleteOnExit();
final FileOutputStream fos = new FileOutputStream(tempFile);
final ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(foo1);
oos.close();
final FileInputStream fis = new FileInputStream(tempFile);
final ObjectInputStream ois = new ObjectInputStream(fis);
final Foo foo2 = (Foo) ois.readObject();
ois.close();
System.out.println("After:\t" + foo2.getValue1() + "\t" + foo2.getValue2() + "\t" + foo2.getValue3());
}
static class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private String value1 = "HELLO";
private transient String value2 = "FOO";
private transient String value3;
public Foo() {
super();
this.value3 = "BAR";
}
public String getValue1() {
return this.value1;
}
public String getValue2() {
return this.value2;
}
public String getValue3() {
return this.value3;
}
}
}
Most safe (and normal) way would be either directly initializing it:
private transient MyClass object = new MyClass();
or using the constructor
public ParentClass() {
this.object = new MyClass();
}
Lazy loading in getters (as you did in your example) is only useful if the constructor and/or initialization blocks of MyClass is doing fairly expensive stuff, but it is not threadsafe.
The transient modifier doesn't make any difference. It only skips the field whenever the object is about to be serialized.
Edit: not relevant anymore. As proven by someone else, they indeed don't get reinitialized on deserialization (interesting thought though, it will actually only happen if they are declared static). I'd go ahead with the lazy loading approach or by resetting them through their setters directly after deserialization.

Categories

Resources