Using try-with-resources with things that are not "resources" - java

I have a continuously running service that I want stopped cleanly if it hits an exception. This fits well with the try with resources paradigm but it's not really a resource that needs to be "closed".
To clarify based on comments, my code looks something like this
class Service {
Resource resource;
State state;
boolean keepRunning = false;
void start() {
keepRunning = true;
resource = new Resource()
new Thread(() -> {
while(keepRunning) {
Data data = resources.pull();
state.update(data);
... // Do stuff with state
}
}).start();
}
void stop() {
keepRunning = false;
}
}
class Main {
void run() {
Service service = new Service();
service.start();
}
}
Is there a pattern that lets me use the syntactic sugar that try-with-resources provides while still not abusing try-with-resources with things that are not resources?

Of course, it is totally okay to use try-with-resources with anything you want. The requirement is that it implements the interface AutoCloseable (documentation). With that interface you will need to implement a close method, which then is called by the try-with-resources construct.
That is why this interface is there, you are allowed to implement it for your own classes.
For example if you have a service that needs to be probably shut down, also in error case, you may use AutoCloseable and implement the close method probably.
However it's meaningless and will confuse readers of your program if you make something AutoCloseable where there is totally no intuition what close means on this object. In such cases you should probably look for other constructs.
It's a bit like implementing Iterable such that you can use the enhanced for loop like:
for (Item item : myObject) {
...
}
You may do it, if it makes sense. Otherwise it will confuse people.

Related

Is terminating an object is the same as nulling it?

So i have been going through "Effective Java 2nd Ed."
In item 7 he talks about not using finalizers because they can cause a lot of problems .
But instead of using finalizers we can " provide an explicit termination method" and an example of those is the close statement . and i did not understand what is " termination statements and what are the differences between them and finalizers ?
I came to the conclusion that terminating an object is like nulling it thus the resourses is released . but i think i don`t understand the difference that well . so i appreciate any help .
Thanks !
But instead of using finalizers we can " provide an explicit
termination method" and an example of those is the close statement .
The authors refers to a close() method that provides a way to clean an object that uses resources to free.
For example when you create and manipulate an InputStream or an OutputStream, you don't want to rely on Java finalizers (that may exist for some subclasses of these interface. For example it is the case for the FileInputStream class that defines a finalize() method) to release the resources associated to the stream but you want to use the method provided by the API to do it : void close() as it is more reliable as finalizer.
java.sql.Statement works in the same way : it provides a close() method to release JDBC resources associated to the statement instance.
I came to the conclusion that terminating an object is like nulling it
thus the resourses is released .
Assigning an object to null will not necessary free all resources that should be freed. Besides if the object or a field of the object is still referenced by another living object, the object would be not illegible to be garbage collected
At last, being garbage collected may also take a some time.
Why wait if we don't need to use the object ?
The main difference between an explicit termination method and finalize() is that the second one is not guaranteed to be called. It's called eventually during garbage collection which might to be honest never occur. Lets consider the following three classes.
class Foo {
#Override
public void finalize() {
System.out.println("Finalize Foo");
}
}
class Bar implements Closeable {
#Override
public void close() {
System.out.println("Close Bar");
}
}
class Baz implements AutoCloseable {
#Override
public void close() {
System.out.println("Close Baz");
}
}
The first one overrides the finalize() method inherited from Object. Foo and Bar implement both interfaces which are handled by ARM (Automatic Resource Management).
Foo foo = new Foo();
new Foo();
try (Bar bar = new Bar(); Baz baz = new Baz()) { // this is ARM
System.out.println("termination example");
}
Bar bar = null;
try {
bar = new Bar();
// ...
} finally {
if (bar != null) {
bar.close();
}
}
This example should return:
termination example
Close Baz
Close Bar
Close Bar
The finalize() method of Foo gets never called because Foo is not garbage collected. The JVM has available resources, so for performance optimization it does not perform garbage collecting. Furthermore - if a resource isn't garbage collected despite the fact of finishing the Application. Even the second created instance of Foo is not Garbage Collected, because there is plenty of resources for the JVM to thrive.
The second one with ARM is a lot better, because it creates both the resources (one implementing java.io.Closeable and one implementing java.lang.AutoCloseable, it's worth mentioning that Closeable extends AutoCloseable, that's why it's available for ARM). ARM guaranties for both of these resources to be closed, to close one when the other throws and so on. The second one presents something similar to ARM, but saving a lot of unnecessary boilerplate code.
Something making you a better developer:
But it's still not perfect. There is still a burden on the programmer to remember closing the object. The absence of destructors in Java forces the developer either to remember closing the resource, remember to use ARM and so on. There is a good design pattern (good explained by Venkat Subramaniam) - the Loan Pattern. A simple example of the loan pattern:
class Loan {
private Loan() {
}
public Loan doSomething(int m) {
System.out.println("Did something " + m);
if (new Random().nextBoolean()) {
throw new RuntimeException("Didn't see that commming");
}
return this;
}
public Loan doOtherThing(int n) {
System.out.println("Did other thing " + n);
return this;
}
private void close() {
System.out.println("Closed");
}
public static void loan(Consumer<Loan> toPerform) {
Loan loan = new Loan();
try {
toPerform.accept(loan);
} catch (Exception e) {
e.printStackTrace();
} finally {
loan.close();
}
}
}
You can use it like that:
class Main {
public static void main(String[] args) {
Loan.loan(loan -> loan.doOtherThing(2)
.doSomething(3)
.doOtherThing(3));
}
}
It relieves the developer of the burden of closing the resource, because it has already been handled for him. If one of these methods throws, then it's handled and the developer does not have to bother. The close method and constructor are private to not tempt the developer to use them.

Java proxy for Autocloseable (Jedis resources)

I am trying to find out whether it is possible to create Java dynamic proxy to automatically close Autocloseable resources without having to remember of embedding such resources with try-resources block.
For example I have a JedisPool that has a getResource method which can be used like that:
try(Jedis jedis = jedisPool.getResource() {
// use jedis client
}
For now I did something like that:
class JedisProxy implements InvocationHandler {
private final JedisPool pool;
public JedisProxy(JedisPool pool) {
this.pool = pool;
}
public static JedisCommands newInstance(Pool<Jedis> pool) {
return (JedisCommands) java.lang.reflect.Proxy.newProxyInstance(
JedisCommands.class.getClassLoader(),
new Class[] { JedisCommands.class },
new JedisProxy(pool));
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try (Jedis client = pool.getResource()) {
return method.invoke(client, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw e;
}
}
}
Now each time when I call method on Jedis (JedisCommands) this method is passed to proxy which gets a new client from the pool, executes method and returns this resource to the pool.
It works fine, but when I want to execute multiple methods on client, then for each method resource is taken from pool and returned again (it might be time consuming). Do you have any idea how to improve that?
You would end up with your own "transaction manager" in which you normally would return the object to the pool immediately, but if you had started a "transaction" the object wouldn't be returned to the pool until you've "committed" the "transaction".
Suddenly your problem with using try-with-resources turns into an actual problem due to the use of a hand-crafted custom mechanism.
Using try with resources pros:
Language built-in feature
Allows you to attach a catch block, and the resources are still released
Simple, consistent syntax, so that even if a developer weren't familiar with it, he would see all the Jedis code surrounded by it and (hopefully) think "So this must be the correct way to use this"
Cons:
You need to remember to use it
Your suggestion pros (You can tell me if I forget anything):
Automatic closing even if the developer doesn't close the resource, preventing a resource leak
Cons:
Extra code always means extra places to find bugs in
If you don't create a "transaction" mechanism, you may suffer from a performance hit (I'm not familiar with [jr]edis or your project, so I can't say whether it's really an issue or not)
If you do create it, you'll have even more extra code which is prone to bugs
Syntax is no longer simple, and will be confusing to anyone coming to the project
Exception handling becomes more complicated
You'll be making all your proxy-calls through reflection (a minor issue, but hey, it's my list ;)
Possibly more, depending on what the final implementation will be
If you think I'm not making valid points, please tell me. Otherwise my assertion will remain "you have a 'solution' looking for a problem".
I don’t think that this is going into the right direction. After all, developers should get used to handle resources correctly and IDEs/compilers are able to issue warnings when autoclosable resources aren’t handled using try(…){}…
However, the task of creating a proxy for decorating all invocations and the addition of a way to decorate a batch of multiple action as a whole, is of a general nature, therefore, it has a general solution:
class JedisProxy implements InvocationHandler {
private final JedisPool pool;
public JedisProxy(JedisPool pool) {
this.pool = pool;
}
public static JedisCommands newInstance(Pool<Jedis> pool) {
return (JedisCommands) java.lang.reflect.Proxy.newProxyInstance(
JedisCommands.class.getClassLoader(),
new Class[] { JedisCommands.class },
new JedisProxy(pool));
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try (Jedis client = pool.getResource()) {
return method.invoke(client, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
public static void executeBatch(JedisCommands c, Consumer<JedisCommands> action) {
InvocationHandler ih = Proxy.getInvocationHandler(c);
if(!(ih instanceof JedisProxy))
throw new IllegalArgumentException();
try(JedisCommands actual=((JedisProxy)ih).pool.getResource()) {
action.accept(actual);
}
}
public static <R> R executeBatch(JedisCommands c, Function<JedisCommands,R> action){
InvocationHandler ih = Proxy.getInvocationHandler(c);
if(!(ih instanceof JedisProxy))
throw new IllegalArgumentException();
try(JedisCommands actual=((JedisProxy)ih).pool.getResource()) {
return action.apply(actual);
}
}
}
Note that the type conversion of a Pool<Jedis> to a JedisPool looked suspicious to me but I didn’t change anything in that code as I don’t have these classes to verify it.
Now you can use it like
JedisCommands c=JedisProxy.newInstance(pool);
c.someAction();// aquire-someaction-close
JedisProxy.executeBatch(c, jedi-> {
jedi.someAction();
jedi.anotherAction();
}); // aquire-someaction-anotherAction-close
ResultType foo = JedisProxy.executeBatch(c, jedi-> {
jedi.someAction();
return jedi.someActionReturningValue(…);
}); // aquire-someaction-someActionReturningValue-close-return the value
The batch execution requires the instance to be a proxy, otherwise an exception is thrown as it’s clear that this method cannot guarantee a particular behavior for an unknown instance with an unknown life cycle.
Also, developers now have to be aware of the proxy and the batch execution feature just like they have to be aware of resources and the try(…){} statement when not using a proxy. On the other hand, if they aren’t, they lose performance when invoking multiple methods on a proxy without using the batch method, whereas they let resources leak when invoking multiple methods without try(…){}on an actual, non-proxy resource…

Java enum that registers as listener on creation

There are two good (as considered by most) java practices that i try to combine and fail.
Never leak this in a constructor.
Use enum instead of singleton pattern.
So, I want a singleton that as soon as created, listens for some event. Here's an example. First, the event listener interface:
public interface EventListener {
void doSomething();
}
Then, the event producer:
public class EventProducer implements Runnable{
private EventListener listener;
public EventProducer(EventListener listener) {
if (listener == null) {
throw new NullPointerException("Listener should not be null.");
}
this.listener = listener;
}
#Override
public void run() {
listener.doSomething(); //This may run before the listener is initialized.
do {
long startTime = System.currentTimeMillis();
long currentTime;
do {
currentTime = System.currentTimeMillis();
} while ((currentTime - startTime) < 1000);
listener.doSomething();
} while (!Thread.currentThread().isInterrupted());
listener = null; //Release the reference so the listener may be GCed
}
}
Then, the enum (as the 2nd listed java practice suggests):
public enum ListenerEnum implements EventListener{
INSTANCE;
private int counter;
private final ExecutorService exec;
private ListenerEnum() {
EventProducer ep = new EventProducer(this); //Automatically unregisters when the producer is done.
counter = 0;
exec = Executors.newSingleThreadExecutor();
exec.submit(ep);
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
}
And finally, something to get things started:
public class TestRunner {
public static void main(String[] args) {
ListenerEnum.INSTANCE.doSomething();
}
}
The problem lies in the first line of the ListenerEnum constructor, as we are leaking this, thus not conforming to the 1st listed java practice. This is why our event producer can call a listener's method before the listener is constructed.
How do I deal with this? Normally I would use a Builder pattern, but how is that possible with an enum?
EDIT:
For those that it matters, the event producer in my program actually extends a BroadcastReceiver, so my enum cannot be the event producer, they have to be separate. The producer is created in the constructor of the enum (as the example) and is registered programmatically later on. So I don't actually have a problem leaking this. Nevertheless, I'd like to know if I could avoid it.
EDIT 2:
Ok, since there are suggestions to solve my problem, i'd like to clarify some things. First of all, most suggestions are workarounds. They suggest doing the same thing in a completely different way. I appreciate the suggestions, and probably will accept one as answer and implement it. But the real question should be "How do i implement a Builder pattern with an enum?" The answer i already know and people suggest is "You don't, do it some other way.". Is there anyone who can post something like "You do! You do it this way."?
I was asked to give code close to my actual use case. Modify the following:
public enum ListenerEnum implements EventListener{
INSTANCE;
private EventProducer ep;
private int counter;
private ExecutorService exec;
private ListenerEnum() {
ep = new EventProducer(this); //Automatically unregisters when the producer is done.
counter = 0;
}
public void startGettingEvents() {
exec = Executors.newSingleThreadExecutor();
exec.submit(ep);
}
public void stopGettingEvents() {
exec.shutdownNow();
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
stopGettingEvents();
}
}
}
As well as this:
public class TestRunner {
public static void main(String[] args) {
ListenerEnum.INSTANCE.startGettingEvents();
}
}
Now all i have to do to solve my problem is move the EventsProducer creation to the startGettingEvents() method. That's it. But that is also a workaround. What i'd like to know is: In general, how do you avoid leaking this in the constructor of a listener enum since you can't use the Builder pattern? Or can you actually someway use the Builder pattern with an enum? Is it done only by workarounds in a case by case basis? Or is there a general way to deal with this that i don't know of?
Just create a static initialization block:
public enum ListenerEnum implements EventListener{
INSTANCE;
private int counter;
private static final ExecutorService exec; //this looks strange. I'd move this service out of enum.
private static final EventProducer ep;
static{
exec = Executors.newSingleThreadExecutor();
ep = new EventProducer(INSTANCE); //Automatically unregisters when the producer is done.
exec.submit(ep);
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
}
As long as enum values are final and static they are initialized before the static initialization block. If you decompile the enum you'll see a single initialization block:
static{
INSTANCE = new ListenerEnum();
exec.submit(INSTANCE.ep);
}
First, consider why this shouldn’t escape:
You loose the final field safe publication guaranty in case of an improper publication of the instance
Even with a safe publication there are inconsistencies regarding all action not performed within the constructor at the time of the leakage
You will let escape an incomplete instance in case of subclasses as the subclass’ constructor hasn’t been called so far
That doesn’t apply to you in this narrow case. Submitting to an Executor is not an improper publication and enum’s can’t escape in any other way besides the one you have implemented yourself in the constructor. And its the last thing in the constructor whereas enums can’t have subclasses.
Now that you have edited your question, it makes much lesser sense. The constructor
private ListenerEnum() {
ep = new EventProducer(this);
counter = 0;
}
is not a “leaking this” as long as ep is not a static variable and the constructor of EventProducer does not let leak its this as well. This is important as programmers must be able to create circular object graphs without fearing sudden inconsistencies.
But it is still nothing you should take too easy. As said, it relies on the behavior of the EventProducer regarding leakage and regarding that EventProducer must not call back into ListenerEnum which could break things without being a “leaking this”, technically. After all, you can create code that breaks without breaking thread safety.
So it’s code for which you can’t see the correctness when looking at it as you need knowledge about another class.
  There are use cases where passing this to another object is considered safe because of well-known behavior, e.g. weakThis=new WeakReference(this); is a real-life example. However, passing this to something called EventProducer is likely to let alarm bells ringing for every reader which you should avoid even if you know for sure that it’s false-alarm.
However, the big design smell lies in the use of the Singleton pattern in itself. After all, every instance you create is unique in the first place. What is special about the Singleton pattern is that it provides global public access to that instance. Is that really what you want? Did you consider that by using the Singleton pattern, everyone inside the entire application could register that listener again?
The fact that your class is a singleton (whether enum-based or otherwise) is unrelated to your problem. Your problem is simply how to register a listener within the constructor of an object. And the answer is: it's not possible, safely.
I would recommend you do two things:
Ensure your listener doesn't miss out on events by having a queue that it polls for work. This way, if it temporarily isn't listening, the work just queues up. In fact, this means it doesn't really need to be a listener in the traditional sense. It just needs to poll on a queue.
Register the class as a listener using a separate method, as discussed in the comments.
I would give some thought to avoiding a singleton. It doesn't offer many advantages (asides from the minor benefit of being able to call SomeClass.INSTANCE from anywhere). The downsides are most strongly felt during testing, where you find it much harder to mock the class when you wish to test without actually sending things over the network.
Here's a concrete example of why leaking this is dangerous in your case. Your constructor passes this before setting counter to zero:
private ListenerEnum() {
ep = new EventProducer(this);
counter = 0;
}
Now, as soon as this escapes, your event producer might invoke doSomething() 5 times before the constructor completes:
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
The sixth call to this method ought to fail right? Except that your constructor now finishes and sets counter = 0;. Thus allowing the producer to call doSomething() 5 more times.
Note: it doesn't matter if you reorder those lines as the constructor may not be executed in the order it appears in your code.

When to use synchronized in Java

I hope this is going to be enough information, so here it goes. If you need more info, lemme know in the comments.
I have a class that has two inner classes. The inner classes each have two methods that call a method in the outer class. So, it looks like this:
public OuterClass {
private boolean outerMethodHasBeenCalled = false;
private void outerMethod() {
if(!outerMethodHasBeenCalled) {
// do stuff
}
outerMethodHasBeenCalled = true;
}
private FirstInnerClass {
public void someMethod() {
outerMethod();
}
}
private SecondInnerClass {
public void someOtherMethod() {
outerMethod();
}
}
}
It's important to note that:
This is for an Android app. Instances of FirstInnerClass and SecondInnerClass are passed to a WebView as a JavaScript interface, so someMethod and someOtherMethod can be called at any time, in no particular order.
I currently have a problem with the existing code (without the synchronized keyword) where outerMethod is called pretty much at the exact same time (I print out a log message, and they're timestamped to the 1000th of a second) by different objects. My app then 'does stuff' twice because outerMethodHasBeenCalled is still false when outerMethod was called. This is not okay, and it is exactly what I'm trying to prevent. My app should only 'do stuff' once and only once: the first time outerMethod is called.
It might sound like I have multiple instances of OuterClass, but rest assured that it's only one instance of OuterClass.
It's important that my app 'does stuff' only the first time outerMethod gets called (I hope that's evident by now). All subsequent calls are essentially ignored. Whichever inner class calls outerMethod first -- doesn't matter.
So, is it appropriate to use the synchronized keyword in this case?
Yup, given what you've laid out above, I'd go with:
private synchronized void outerMethod() {
...
}
Note, this will have the side-effect of blocking one of the callers until the outerMethod() completes. If that is acceptable, cool. If the intent is merely that the code in outerMethod() is run once, and it is OK for the second caller not to be delayed if the first caller is running outerMethod(), you might consider:
public OuterClass {
private AtomicBoolean outerMethodHasBeenCalled = new AtomicBoolean();
private void outerMethod() {
if (outerMethodHasBeenCalled.compareAndSet(false, true)) {
// do stuff
}
}
...
See the JavaDoc for AtomicBoolean to grok what is going on there (assuming it is available in Android's Java).
Wrap everything in outerMethod that you want to run only once in a synchronized block:
private void outerMethod() {
synchronized (this) {
if(!outerMethodHasBeenCalled) {
// do stuff
}
outerMethodHasBeenCalled = true;
}
}
That way, the first time the method is called, only one thread will be allowed into the synchronized block at a time. The first one will execute the code in the if statement, then set outerMethodHasBeenCalled to true. The other threads will see that it is true, and skip the if code.

Create a timeOut class in java

I would like to create a java class (thread) that pings twitter and if there is no connectivity wait until there is connection and re-run some other classes and threads.
I have the code that "pings" websites and a way to run every static method is in my Main class. Is this a good solution to the problem?
Here is the basic part of the code:
while (true){
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
}
catch (Exception e) {
Thread.sleep(10000*t);
if (url.matches(twitter1)){
Thread method1= new Thread(Class1.method1);
method1.start();
}else if (url.matches(twitter2)){
Thread method2 = new Thread(Class1.method2);
method2.start();
}else if (url.matches(twitter3)){
Main.StaticMethod();
}else if (url.matches(twitter4)){
Main.StaticMethod2();
}else if (url.matches(twitter5)){
Main.StaticMethod3();
}else{
System.out.println("Unknown URL");
}
t=2^t;
}
}
You do not run classes or threads, you can only invoke methods. If the methods are instance methods then you need some object; otherwise they are static and you need to know the class in which they are defined. If you want to start another thread, then you need an object of a class that implements Runnable.
For example,
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
} catch (Exception e) {
}
// connection is available, either use it or close it. then,
// AfterConnect is a class that implements Runnable. Perhaps it takes
// the connection as parameter?
AfterConnect afterConnect = new AfterConnect(..);
// this will start a new thread
new Thread(afterConnect).start();
BTW your example does not "wait until there is connection". If you are going to put the try...catch in a loop, you should sleep for some time between iterations.
How will you define "running" the classes ? One way to do it would be to store references to these classes in your timeOut class, and then to invoke the methods that you want when you successfully ping the site.
I'm not quite sure how you have structured the "re-run some other classes and threads" stuff. If it is in a mishmash of method calls, then you could put the code you presented in an abstract class, and add an abstract method
abstract class AbstractTimeout {
... your code here, but add a call to afterConnection() ...
protected abstract void afterConnection();
}
A subclass would implement that by setting up some fields for all the classes objects and calls in a constructor, then implementing the mishmash of calls in
protected void afterConnection() {
class1.goDoThis();
object2.goDoThat();
someRunnable.run();
// ... etc...
}
This is classic inheritance. BTW, you need to consider what Exceptions might be thrown and which to declare. For simplicity, I ignored that issue.
Alternatively, if the "re-run some other classes and threads" stuff is already in something fairly simple and well organized like a Runnable, you could have your class take a Runnable along with the URLConnection as an argument, and run() the Runnable (or launch it in a new thread) after the connection is complete. This is classic composition. e.g.
public void doTimeout(URL url, Runnable afterConnection) {
// your connection stuff from above
afterConnection.run();
}
NOTE : I didn't put afterConnection.run() into a Thread, cause I think that doTimeout should already be in it's own thread. YMMV.
NOTE2: My 2nd solution is similar to #Miserable Variable afterConnect() concept. I used a Runnable, he used a a more flexible interface.

Categories