Reputation: 9720
I am writing an SshConnectionPool, which stores and returns SshConnections. The idea is that a user should do something like this:
SshConnection sc = SshPool.getInstance().getConnection(server, user, password, port);
// use connection in some way
SshPool.getInstance().release(sc);
And after that I want the sc
reference to be unusable. I know I can't set it to null in the implementation of the release()
method. But how can I do that?
Upvotes: 0
Views: 298
Reputation: 9720
For the brave who will someday follow my footsteps:
What I did eventually was: I declared the SshSession
as an interface and created 3 implementations of it: a real/live/working session (RealSession
) which has all functionality, the variables are set to real values and methods do real work (e.g. exec(String command)
will execute a command on a remote machine), a dummy session (DummySession
) which has all the ivars, but throws exceptions when "doing" methods are called (e.g., it returns real host name on ssh.hostname()
, but throws an exception on ssh.exec(command)
, and a session wrapper that has an SshSession
implementation within it and all the methods in the session wrapper call the corresponding methods on the wrapped session.
The SshPool
stores within it a map of RealSession
s, but returns a SessionWrapper
with a RealSession
wrapped into it. So outside of the pool you can only deal with SessionWrapper
s. Thus, when you call pool.release(sessionwrapper)
, the pool returns the session from the wrapper into the pool, and puts a DummySession
into the wrapper. That way you can still access the info about the session (e.g. host, user, etc), but cannot call any methods on it.
I know some code would not go amiss, but I hope the description is clear enough.
Upvotes: 0
Reputation: 121780
No idea how you will "reuse" SshConnection
objects but anyway, my suggestion is that you:
SshPool
itself;SshConnection
object implement Closeable
, and in .close()
, give the object back to the pool.As in:
private final SshPool pool;
SshConnection(final SshPool pool, other parameters)
{
this.pool = pool;
// etc
}
@Override
public void close()
throws IOException
{
pool.release(this);
// other instructions here
}
This means among other things that you'll be able to use such objects in a try-with-resources statement; and the only requirement on the user of the API is that they .close()
once used, which they should do anyway for any Closeable
object.
Upvotes: 2
Reputation: 1979
If i understood the question correct..then u need to make the class as immutable
with that the object instance will be usable by the variable but for any change the object will be discarded and a new instance will be created
Upvotes: 0