What are the ways to create spring bean thread-safe
Answer»
Create immutable beans
Immutable CLASS means that once an object is created, we cannot change its content. In Java, all the WRAPPER classes (like String, BOOLEAN, Byte, Short) and String class are immutable. We can create our own immutable class as well.
// An immutable class
public FINAL class Student
{
final String name;
final int regNo;
public Student(String name, int regNo)
{
this.name = name;
this.regNo = regNo;
}
public String getName()
{
return name;
}
public int getRegNo()
{
return regNo;
}
}
Create stateless beans
A Stateless object is a special instance of the class without the instance variables. All fields are static final. You can SAY it is immutable. It may have a state but it does not change. These kind of instances are by default thread-safe.
class Stateless
{
//No static modifier because we're talking about the object itself
final String TEST = "Test!";
void test() {
System.out.println(TEST);
}
}
Design persistent beans - a special case of immutable.