简体   繁体   中英

Effect of Singleton classes in Webservices

I am implementing a webapplication and providing few rest APIs.

Following is the structure of my webapplication.

Service Layer
Service class contains different APIs.

It invokes DAO which is a singleton class (I would rather say that it is an Enum and only instance has been defined for Enum ) and it does not have any state. I mean there are no instance variable in DAO layer classes.

DAO Layer
DAO class fetches DB connection (DB connection is provided through Enum class, and I created the connection at the time of instantiating the Enum ), and it execute respective query on the DB.

So Application architecture is like this.

ServiceClass {
    Dao.operation()
}

DaoEnum {

    instance;

    operation() {
        DBConnectionEnum.instance.connection.preparedStmt.respective operation
    }
}

DBConnectionEnum {
    DBConnectionEnum() {
        grabDBConnection()
    }
}

I understand I have to use connectionpool to grab db connection, but I am unable to understand the impacts caused by Dao layer, which is singleton.

Could you suggest me whether it is a correct design, or will it exhaust the application? What improvements can be made to make application more robust, fast and performant?

the Singleton design pattern is a good pattern on its own, otherwise it would not have lasted this long. There are some drawbacks , like introducing global state into your application. But I don't think those downsides are enough to discount it. However there are better ways of doing what you're trying to do. Dependency Injection is one way of abstracting invocation from implementation. You can even use a Singleton in your DI Implementation, as long as it's transparent from the invocation. I would highly recommend that you do some research on DI.

I was discussing the issue with my colleague and as per the discussion I felt my singleton DAO layer must not cause any issues for me.

As DAO layer is working as a mediator between DB and Service class, and DAO layer do not maintain any state. So when 2 similar requests are invoked simultaneously, then both requests will be served in 2 different threads and each thread will maintain its own Stack. When both the requests call DAO layer, these requests will simply invoke DAO layer's method which will be associated with the respective thread's stack.

So If I create Singleton DAO layer in my application to serve multiple web requests, it will not exhaust throughput and clients must be served without any issue.

Hope I am making little sense. :)

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