开发者

store variable in application scope java glassfish

i'm trying to store a number in the applicationscope of a glassfish webservice

the webservice:

@WebService()
public class datacheck {
    //TODO 080 disable sql_log in the settings of hibernate
    //TODO 090 check todo's from webservice_1

    private int counter = 5;

when i request the counter variable i get 5 and

@WebMethod(operati开发者_JAVA技巧onName = "increaseCounter")
public Integer increaseCounter() {
    counter++;
    return counter;
}

returns 6 but when i try to do this afterwards i get 5 again:

@WebMethod(operationName = "getCounter")
public Integer getCounter() {
    return counter;
}

how do i store a variable that is available for all methods in the webservice?


This depends on your use case and architecture to an extent. If every user should see the result of increment counter then yo could declare it statically in your code.

private static int counter = 5;

This will only work if you have only one JVM in your application though and would require careful thought about synchronization.

Alternatively you could persist it externally ( to a database or file for example )


Implementing the Singleton pattern should work. you will end up with the same instance in the whole JVM. Beware though: writing to a singleton from different threads might be a contented lock, and that way be dragons!

There's also ThreadLocal if you want to constraint an object to one thread (i think glassfish is one thread per request but dont cite me :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜