I’m learning REST by going thru this tutorial. It first runs: ClientAllOrders()
, which creates 5 orders. Then it runs: ClientDeleteById()
, which deletes orders 2 and 4. Then it runs ClientAllOrders()
, and gets all orders except for orders 2, 4. It creates orders here:
public enum OrderService {
Instance;
private Map<Integer, Order> orders = new HashMap<>();
OrderService() {
Instant instant = OffsetDateTime.now().toInstant();
for (int i = 1; i <= 5; i++) {
Order order = new Order();
order.setId(i);
order.setItem("item " + i);
order.setQty((int) (1 + Math.random() * 100));
long millis = instant.minus(Period.ofDays(i))
.toEpochMilli();
order.setOrderDate(new Date(millis));
orders.put(i, order);
}
}
//---
}
These are the GET and DELETE methods:
@Path("/orders")
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
public class OrderResource {
@GET
public Collection<Order> getOrders() {
return OrderService.Instance.getAllOrders();
}
@DELETE
@Path("{id}")
public boolean deleteOrderById(@PathParam("id") int id) {
return OrderService.Instance.deleteOrderById(id);
}
//…
}
Unless I stop/start the server or deploy a new war, the OrderService.constructor
is called only ones, no matter how many times getOrders()
or deleteOrderById()
are called. The OrderService.constructor
is called only when the OrderService.Instance
object is null, but why all the OrderService.Instance
objects in OrderResource
class refer to the same object – hence the OrderService.Instance
is null only when one of the methods in OrderResource
is called for the first time and all subsequent calls, refer to the same object which is not null anymore, considering the OrderService
is not a Singleton and the constructor is not private.