How can I reuse an instance of a webservice? - java

I am running a service A which has a class X. I am going to deploy another service B on same machine which is using this class X. How can I make sure that the same instance of service A is reused instead of another.
PS:Service written in JAVA.
Adding: Both these services are Axis2 services. Service B is hot-deployed. Service B used class Y which is extension of class X.

Could we try to distinguish classes, objects and services.
You have something like this?
#javax.jws.WebService
public class ServiceAAA{
public String echo(String arg) {
// some really nice code here
}
}
and you want to add
#javax.jws.WebService
public class ServiceBBB{
public String superEcho(String arg) {
// even more code here
// which needs to reuse the code from A's echo()
}
}
So clearly we don't want to cut and paste between the two implementations. How do we reuse?
Alternative 1:
Directly call A from B. You are asking how to do that. It could be done. You would just code a JAX-WS client call in your implmentation. However I stringly recommend against this. A service call is likely to be more expensive than a simple Java call.
Only do this if y6ou don't have the option of deploying the two service classes together.
Alternative 2:
Refactor the implementation. Just move the code into a worker class.
#javax.jws.WebService
public class ServiceAAA{
MyWorker worker = new Worker();
public String echo(String arg) {
return worker.doSomething(arg) ;
}
}
#javax.jws.WebService
public class ServiceBBB{
MyWorker worker = new Worker();
public String superEcho(String arg) {
worker.doSomething(arg) ;
// and some morestuff
}
}

Don't know java, but you could make use of a singleton pattern on the objects your are trying to use.
edit: I think you should have class X implementing the singleton pattern...

I understand that A uses an object of class X, and B too.
Configure your two webServices A and B to use the same instance of object X.
This configuration could be done by several means, for example:
in your starting sequence, create an instance X and assign it via setX(x) to each webService.
or you could do this in a Constructor, using static fields
Example:
#javax.jws.WebService
public class A implements WebService {
public static final X x = new X();
public void methodA() {
// use x
}
}
#javax.jws.WebService
public class B implements WebService {
private Y y = new Y(A.x);
public void methodB() {
// use y that uses x.
y.methodY();
}
}
public class Y {
private final X x;
public Y(X x) {
this.x = x;
}
public void methodY() {
// use x, it is the same instance as in A
}
}

Related

Design pattern for similar functions with lambdas

I am trying to figure out a way or a pattern to simplify my Service class and make it very adjustable. My aim would be for the method in Service class to be accessed for example with lambdas or Predicates.
class Client {
#RequestLine("something/a")
public A fetchA() {}
#RequestLine("something/b")
public B fetchB() {}
//... lots of similar methods
#RequestLine("something/z")
public Z fetchZ() {}
}
class Service {
Client client;
public void fixA(){
client.fetchA();
method();
}
public void fixB(){
client.fetchB();
method();
}
// ... lots of similar methods
public void fixZ(){
client.fetchZ();
method();
}
void method() {}
}
So my point how I could change it so it would use lambdas or something that would leave my Service class with one of the "fix" methods but it would know what I need to fetch from my Client.
If this question is bad and does not comply with rules here then please point me in the right direction as I am lost.
I guess what you want is
class Service {
private Client client;
public void fix(Consumer<Client> consumer){
consumer.accept(client);
method();
}
private void method() {}
}
that you can call using
service.fix(Client::fetchB);
One way would be to pass the call to your client as an argument to the method of your service. You'd need to use generics:
class Service {
Client client;
public <T> void fix(Function<Client, T> clientCall) {
T result = clientCall.apply(client);
// Do something with result
method();
}
}
You would need to call your service fix method as follows:
service.fix(Client::fetchA);
This question may be somewhat opinion based but let’s give it a try.
From my point of view the first design flaw you made is to put all the fetchXYZ methods into one client. You could create an interface Client that might look like this
interface Client<T> {
T fetch();
}
And create implementations of this interface like this:
public class ClientA implements Client<A> {
#RequestLine(”something/a“)
public A fetch() {
// do fetch stuff
}
}
You could store instances of the client implementations locally in a map or use a Factory pattern to create the right client depending on your input. And finally the fix method in your service might look like this:
public void fix(String clientType) {
// returns instance of ClientA for ’a‘ for example
final Client client = getClientForType(clientType);
client.fetch();
method();
}
There‘re probably plenty of ways to solve your requirements and this is just one of them.
I personally don’t like the idea of passing the client function as parameter to your method (although you asked for it) as in your current design Client has different responsibilities (fetches A, B and so on). Using lambdas actually enforces this flaw and furthermore hides what Client actually does.
Just my 2 cents.
Usually the point of Service is to be a facade over the Client. If that is the case with your example and you dont want to expose Clent class to the caller of Service you can go with single method and an enum like this:
public class Service {
Client client = new Client();
public enum FixType{
A(Client::fetchA),
B(Client::fetchB),
Z(Client::fetchZ);
private Consumer<Client> c = null;
private FixType(Consumer<Client> c) {
this.c = c;
}
private void fix(Client client) {
c.accept(client);
}
}
public void fix(FixType ft) {
ft.fix(client);
method();
}
void method() {}
}
And call fix by passing one of enums:
new Service().fix(Service.FixType.B);
Why not just
class Client {
public A fetch (String identifier) {
ArrayList<String> identifiers = ...;
// validate user-provided identifier here
if (___.equals(identifier)) {
// specific code for each identifier
} else if {
// ...etc.
}
}
}
class Service {
Client client;
public void fix (String identifier){
client.fetch(identifier);
method();
}
void method() {}
}

How do you automatically pass all nested static classes into a method call as a parameter?

Is there a way of retrieving an array of static classes within the Network class (defined below), and pass each class's attribute class into a parameter of a method call kryo.register?
public class Network {
// Classes to be transferred between the client and the server
public static class A {
public int id;
public String name;
}
public static class B {
public int id;
public int x;
public int y;
}
// Rest of the classes are defined over here
static public void register(EndPoint endPoint) {
Kryo kryo = endPoint.getKryo();
// typical way of registering classes so that kryonet can use it
// kryo.register(A.class);
// kryo.register(B.class);
// the rest of the classes are registered with kryonet over here
// my attempt at solving the question,
// but for some reason this doesn't work?
for(Object o : Network.class.getDeclaredClasses()) {
kryo.register(o.getClass());
}
}
}
The problem is that you are using the class of the class, which isn't what you want. if you used the correct type for the result of the getDeclaredClasses() call, it would have been more obvious:
for(Class<?> c : Network.class.getDeclaredClasses()) {
kryo.register(c);
}
(btw, you are already using reflection -> getDeclaredClasses()).

Pass an object of another class to a singleton class

I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.

Edit an object's methods after they've been created in Java

In JavaScript one can create and edit an object's functions on the fly. Is this possible with a Java object's methods? I am essentially wanting something like this:
public class MyObject{
private int x;
public MyObject(){x = 0;}
public myMethod(){}
}
MyObject foo = new MyObject();
and later call something along the lines of:
foo.myMethod = new method({x = 42;});
It's not directly possible, but you could try something like this:
public class MyObject {
private int x;
interface MyMethod {
void call();
}
public MyObject() {
x = 0;
}
public MyMethod myMethod = new MyMethod() {
#Override
public void call() {
x = 42;
}
};
}
You can't edit it in the way that you are trying to demonstrate above, the closest thing you could do to emulate it would be to intercept the method. The only way I could think of at the current moment is to use a MethodInterceptor found within the cglib library to intercept the method.
In Java you cannot do this like you would do it in Javascript.
But in Java you can achieve such an behavior using the Strategy pattern.
For example,
public interface Strategy {
void doSomething(MyObject obj);
}
public class BasicStrategy implements Strategy {
public void doSomething(MyObject obj) {
//do something
}
}
public class AnotherStrategy implements Strategy {
public void doSomething(MyObject obj) {
obj.setX(42);
}
}
public class MyObject {
private Strategy actualStrategy = new BasicStrategy();
private int x = 0;
public void executeStrategy() {
actualStrategy.doSomething(this);
}
public void setStrategy(Strategy newStrategy) {
actualStrategy = newStrategy;
}
public void setX(int x) {
this.x = x;
}
}
You can alter the behavior of the method at runtime using the following code.
MyObject obj = new MyObject();
obj.setStrategy(new AnotherStrategy());
obj.executeStrategy();
Yes, it's theoretically possible, but you don't want to do it. This sort of thing is black magic, and if you need to ask the question, you're several years from being ready to work with it.
That said, what you're trying to accomplish may be workable with the Strategy design pattern. The idea here is that you define an interface that has the method(s) you need to swap out (say, calculate()), and the class whose behavior you want to change has a field of that interface. You can then modify the contents of that field.
public interface Calculator {
double calculate(double x, double y);
}
public class MathStuff {
private Calculator calc;
...
public void doStuff() {
...
result = calc.calculate(x, y);
...
}
}
public class Add implements Calculator {
public double calculate(double x, double y) {
return x + y;
}
}
You cannot do this. In java new method is made to return the instance of class Object, not methods. And one thing is to understand is Javascript is an functional programming language and Java is a object oriented language. You cannot treat a method as object in java, also it breaks the security of java encapsulation.

Per thread singleton pattern

In my work I stumbled upon such a design issue:
I need one instance of a Manager class per thread
These instances should be globally accessible, like in the singleton pattern via a static function
Each thread might need to initialize its instance with different arguments
The lifetime of these instances should be controllable, sometimes it would be beneficiary to remove an instance and allow GC to collect it
The first two points would make it a 'per thread singleton' if such a thing exists.
This is what I came up with (the code is simplified, I've omitted safety checks and so on):
public class Manager {
private final static ThreadLocal<Manager> local = new ThreadLocal<Manager>();
private int x;
Manager(int argument) { x = argument; }
public static void start(int argument) { local.set(new Manager(argument); }
public static void clean() { local.remove(); }
private void doSomething1() { x++; .... }
private int doSomething2() { if (--x == 0) clean(); ... }
public static void function1() { local.get().doSomething1(); }
public static int function2() { return local.get().doSomething2(); }
}
As you can see the clean function can be also called from within the private methods.
Also notice that through the use of static functions the reference to the instance is never leaked, so instances assigned to different threads won't get mixed.
This works quite ok, but then I got another requirement:
Different threads may need to utilize different implementations of Manager class
So I defined an interface:
public interface ManagerHandler {
void method1();
int method2();
}
And modified the Manager class:
public class Manager {
private final static ThreadLocal<ManagerHandler> local = new ThreadLocal<ManagerHandler>();
public static void start(int argument) {
ManagerHandler handler;
// depending on the context initialize handler to whatever class it is necessary
local.set(handler);
}
public static void clean() { local.remove(); }
public static void function1() { local.get().method1(); }
public static int function2() { return local.get().method2(); }
}
An example implementation would look like this:
public class ExampleManagerImplementation implements ManagerHandler {
private int x;
public ExampleManagerImplementation(int argument) { x = argument; }
public void method1() { x++; .... }
public int method2() { if (--x == 0) Manager.clean(); ... }
}
Manager class works here as a facade, forwarding all the calls to the appropriate handler. There is one big issue with this approach: I need to define all the functions both in the Manager class and in the ManagerHandler interface. Unfurtunately Manager class can't implement ManagerHandler interface, because it has static functions rather than methods.
The question is: can you think of a better/easier way to accomplish all the goals I've listed above that would be free of this issue?
There is not much you can do, as you basically need to proxy interface methods through static methods. I could only think of two ways to achieve the same functionality differently:
If you're using a DI framework, you can get rid of the static Manager and use an injected implementation of ManagerHandler which will contain the ThreadLocal.
Generate (as in 'bytecode generation') the static ManagerAccess class using the methods found in the ManagerHandler interface.
Personally, I wouldn't think of having the static ManagerAccess class (which contains the ThreadLocal) around as a serious design issue. At least as long as it keeps to its own set of responsibilities (accessing thread-scoped instances and proxying calls) and doesn't venture anywhere else.
If you're going with this design, is it necessary for Manager to totally hide ManagerHandler interface, or could you expose it so you don't have to delegate every method?
class Manager {
public static ManagerHandler getHandler() { return local.get(); }
}
The trick for creating a singleton per thread class is to use ThreadStatic attribute on your private static _current field which makes it scoped by thread. In this way, the _current field will be stored inside thread memory which is not accessible for the other threads and not shared memory of AppDomain. So, it will be available only in the scope of the thread. On the other hand, the Current property is accessible across all threads in that AppDomain but when it is called it will return the correct instance for that thread. Here is the code that you need:
public sealed class Manager
{
// As you are using the ThreadStatic here you cannot
// call the static constructor or use the Lazy implimentation for
// thread-safty and you have to use the old fashin Lock and anti-pattern.
private static readonly object _criticalArea = new object();
[ThreadStatic]
private static Manager _current;
public static Manager Current
{
get
{
if (_current == null)
{
lock (_criticalArea)
{
if (_current == null)
{
_current = new Manager();
}
}
}
return _current;
}
}
private Manager()
{
}
public string WhatThreadIsThis { get; set; }
}
[TestClass]
public class SingeltonPerThreadTest
{
private readonly EventWaitHandle _threadHandler = new EventWaitHandle(false, EventResetMode.AutoReset);
private string _sharedMemory = "I am the shared memory and yet in main thread :(";
[TestMethod]
public void TestSingeltonPerThread()
{
// Creates a _current for main thread.
Manager.Current.WhatThreadIsThis = "I am the main thread :)";
// Start another thread.
(new Thread(CallTheThreadBaseSingelton)).Start();
// Wait for it to be finished.
_threadHandler.WaitOne();
Assert.AreEqual("I am the main thread :)", Manager.Current.WhatThreadIsThis, "I am not the main thread :( ");
Assert.AreEqual("I am the other thread ;)", _sharedMemory, _sharedMemory);
}
private void CallTheThreadBaseSingelton()
{
// Creates a _current for this thread (this thread is the other one :)) ).
Manager.Current.WhatThreadIsThis = "I am the other thread ;)";
_sharedMemory = Manager.Current.WhatThreadIsThis;
_threadHandler.Set();
}
}
Cheers.

Categories

Resources