Does java have an equivalent to the C# "using" clause - java

I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent?

Yes. Java 1.7 introduced the try-with-resources construct allowing you to write:
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
... just like a using statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is 2 */
} finally {
is2.close();
}
} finally {
is1.close();
}

Yes, since Java 7 you can rewrite:
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
As
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
The objects passed as parameters to the try statement should implement java.lang.AutoCloseable.Have a look at the official docs.
For older versions of Java checkout this answer and this answer.

The nearest equivalent within the language is to use try-finally.
using (InputStream in as FileInputStream("myfile")) {
... use in ...
}
becomes
final InputStream in = FileInputStream("myfile");
try {
... use in ...
} finally {
in.close();
}
Note the general form is always:
acquire;
try {
use;
} finally {
release;
}
If acquisition is within the try block, you will release in the case that the acquisition fails. In some cases you might be able to hack around with unnecessary code (typically testing for null in the above example), but in the case of, say, ReentrantLock bad things will happen.
If you're doing the same thing often, you can use the "execute around" idiom. Unfortunately Java's syntax is verbose, so there is a lot of bolier plate.
fileInput("myfile", new FileInput<Void>() {
public Void read(InputStream in) throws IOException {
... use in ...
return null;
}
});
where
public static <T> T fileInput(FileInput<T> handler) throws IOException {
final InputStream in = FileInputStream("myfile");
try {
handler.read(in);
} finally {
in.close();
}
}
More complicated example my, for instance, wrap exceptions.

It was a long time coming but with Java 7 the try-with-resources statement was added, along with the AutoCloseable interface.

Not that I'm aware of. You can somewhat simulate with a try...finally block, but it's still not quite the same.

The closest you can get in Java is try/finally. Also, Java does not provide an implicit Disposable type.
C#: scoping the variable outside a using block
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
X x = new X();
using(x) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable outside a block
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}
C#: scoping the variable inside a block
public class X : System.IDisposable {
public void Dispose() {
System.Console.WriteLine("dispose");
}
private static void Demo() {
using(X x = new X()) {
int i = 1;
i = i/0;
}
}
public static void Main(System.String[] args) {
try {
Demo();
} catch (System.DivideByZeroException) {}
}
}
Java: scoping the variable inside a block
public class X {
public void dispose() {
System.out.println("dispose");
}
private static void demo() {
{
X x = new X();
try {
int i = 1 / 0;
} finally {
x.dispose();
}
}
}
public static void main(String[] args) {
try {
demo();
} catch(ArithmeticException e) {}
}
}

I think you can achieve something similar to the "using" block, implementing an anonymous inner class. Like Spring does with the "Dao Templates".

Well, using was syntactic sugar anyway so Java fellows, don't sweat it.

If we get BGGA closures in Java, this would also open up for similar structures in Java. Gafter has used this example in his slides, for example:
withLock(lock) { //closure }

The actual idiom used by most programmers for the first example is this:
InputStream is1 = null;
InputStream is2 = null;
try{
is1 = new FileInputStream("/tmp/bar");
is2 = new FileInputStream("/tmp/foo");
/* do stuff with is1 and is 2 */
} finally {
if (is1 != null) {
is1.close();
}
if (is2 != null) {
is2.close();
}
}
There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.
Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.

No there isn't.
You can
public void func(){
{
ArrayList l = new ArrayList();
}
System.out.println("Hello");
}
This gives you the limited scope of the using clause, but there isn't any IDisposable interface to call finalization code. You can use try{}catch(){}Finally{}, but it doesn't have the sugar of using. Incidentally using finalizers in Java is generally a bad idea.

No, there is no using in Java, the most similar functionality is the "import" keyword.

Related

Continue from the next line after getting exception

I want to continue with the next line from which error generated,
try{
statement A;
statement B;
statement C;
}
catch(NullPointerException NPE){.....}
Now assume that my statement A throws exception so I want to skip that and continue with B. Don't give my suggestion to put in catch/finally block or any other solution. I just want to know is this possible to skip and continue with next statement?
Yes, it is possible without the finally block.
try{
statement A;
}
catch(NullPointerException NPE){.....}
try{
statement B;
}
catch(NullPointerException NPE){.....}
try{
statement C;
}
catch(NullPointerException NPE){.....}
On the side note, I don't really think this is nice. If you managed to come to the point where you need this kind of flow control, you need to take a step back and rethink your code design.
It is not possible to execute statement B if A throws exception. One way is seperately try/catch block and other way is put other lines into finally block.
If your statements are similar and can be paramerized, use a loop:
for (int i = 0; i < statementCount; i++) {
try {
/** do what you need */
} catch(Exception e) {
}
}
or put it in separate method if it needs more parameters:
public static void main(String[] args) {
for (int i = 0; i < statementCount; i++) {
}
execute(params);
}
public void execute(Object... objects) {
try {
doSomthing(objects[0], objects[1]);
} catch(Exception e) {
}
}
If statements are abolutely different, Java 8 provides interesting solutions: method references and lambdas. So you can play arround with somthing like this:
public static void main(String[] args) {
execute(someObject, YourClass::method);
}
public void execute(Object param, Function<Object, Void> function) {
try {
function.apply(param);
} catch(Exception e) {
}
}
Like darijan already mentioned you could put every single statement into an own try-catch. Or if you know what may cause the exception you can simply check it befor you execute your statements
try{
if(parameterForStatementA != null) {
statementA;
}
if(parameterForStatementB != null) {
statementB;
}
if(parameterForStatementC != null) {
statementC;
}
} catch(Exception e) {
// something unexpected happened
}
Verifying parameters is usually more efficient than catching thrown exceptions

Queue Error in java

I had implemented a asynchronous thread by a singleton class in which a queue is present to which i add logging object.
But it is giving no such element exception at java.util.linkedlist.remove
public class LogDaoSingleton extends Thread {
private static LogDaoSingleton logDaoSingleton = new LogDaoSingleton();
private static Queue<ScoreLoggingObject> queue = new LinkedList<ScoreLoggingObject>();
private static Boolean firstTime = true;
private LogDAO logDAO;
private SkipLogDaoImpl skipLogDAO;
Connection conNull = null;
Connection connection = null;
private int counter = 0;
Connection con = null;
Connection skipCon = null;
public static LogDaoSingleton getInstance() {
return logDaoSingleton;
}
private static void createInstance() {
logDaoSingleton = new LogDaoSingleton();
}
private LogDaoSingleton() {
try {
con = HMDBUtil.getNonTxNullProdConnection();
conNull = HMDBUtil.getNonTxNullProdConnection();
skipCon = HMDBUtil.getNonTxNullProdConnection();
logDAO = new LogDAOImpl();
skipLogDAO = new SkipLogDaoImpl();
hmCandScoreLog = PropertyReader.getStringProperty(
CacheConstants.CLUSTER_REPORT,
CacheConstants.HM_CAND_SCORE_LOG);
hmCandScoreLogNull = PropertyReader.getStringProperty(
CacheConstants.CLUSTER_REPORT,
CacheConstants.HM_CAND_SCORE_LOG_NULL);
} catch (HMCISException e) {
e.printStackTrace();
}
}
public static void addtoQueue(ScoreLoggingObject scoringObject) {
queue.add(scoringObject);
if (firstTime) {
synchronized (firstTime) {
if (firstTime) {
createInstance();
logDaoSingleton.setDaemon(false);
logDaoSingleton.start();
firstTime = false;
}
}
}
}
public void run() {
try {
while (true) {
try {
if (null != queue && queue.size() > 0) {
logData(queue.poll());
} else {
try {
Thread.sleep(2 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
// Do nothing.
}
}
} catch (Throwable e) {
firstTime = true;
}
}
private void logData(ScoreLoggingObject scoreLoggingObject) {
}
}
}
Error is at logData(queue.poll());
There are at least three problems in this method:
public static void addtoQueue(ScoreLoggingObject scoringObject) {
queue.add(scoringObject);
if (firstTime) {
synchronized (firstTime) {
if (firstTime) {
createInstance();
logDaoSingleton.setDaemon(false);
logDaoSingleton.start();
firstTime = false;
}
}
}
}
Namely
That you are adding to a LinkedList without a lock. LinkedList is not a concurrency safe collection. Try ConcurrentSkipLinkedList as a better collection.
You are reading firstTime using double-checked locking... which can have side-effects that you might not believe... Go take a look at "Java Concurrency in Practice" specifically the Yuck-face listing on page 32. Try to predict what that program will output before reading the book. Then read the explanation. Unfortunately I am going to have to spoil the impact of that example for you now when I point out that the JVM is entitled to reorder operations in between synchronization points. So the result is that the operations within your synchronized block can be implemented in any order... for example they could happen in the following order (likely not, but a JVM implementation will still be valid if it did it in this order)
synchronized (firstTime) {
if (firstTime) {
firstTime = false;
createInstance();
logDaoSingleton.setDaemon(false);
logDaoSingleton.start();
}
}
What would happen if there is an exception thrown in your createInstance() method?
If it were me, I would fix that by making firstTime a volatile that would force the JVM to respect the ordering (though you would still need the double-check!)
firstTime is a Boolean initialized by auto-boxing, which for Boolean uses pooled instances, so your double-checked lock is actually synchronized (Boolean.TRUE) and not synchronized (firstTime). Additionally it is bad form to synchronize on a non-final field, as it almost never does what you want it to do. You probably want to just make the addToQueue method synchronized until you know you have a problem.
TL;DR you are trying to be 'clever' with locking... always a bad plan... especially before you know that you need to be clever. Write the simplest thing that could possibly work, then get on with the rest of the problems. Then see where the performance issues are... ONLY THEN should you worry about locking in this class.

Restart myself - can I reinitialize everything from scratch?

I have something like this:
public static final String path;
static {
path = loadProperties("config.conf").getProperty("path");
}
public static void main(String... args) {
// ... do stuff (starting threads that reads the final path variable)
// someone want's to update the path (in the config.conf file)
restart(); // ???
}
I want to reinitialize the JVM calling the static initializer again, and then main(...)!
Can it be done?
You can start your application using a custom class loader, this will allow you to load and unload your static variables.
However, basically its a very bad design to need to do this. I like making fields final, but you shouldn't make them final if you want to change them.
If your goal is simply to reload some configuration files, why not implement a file change monitor?
Here's a good tutorial on this subject:
http://download.oracle.com/javase/tutorial/essential/io/notification.html
I think what you're proposing (restarting your application automatically) would be a little more cumbersome than just watching for file updates.
A simpler approach is simply not to use the static initializer for this. Why not just make path non-final and load it in main?
I'm accepting Peter Lawrey answer but post a complete example for anyone to use!
I'm not going to use this in production code... there are other ways of doing it!
public class Test {
public static void main(String args[]) throws Exception {
start();
Thread.sleep(123);
start();
}
private static void start() throws Exception {
ClassLoader cl = new ClassLoader(null) {
protected java.lang.Class<?> findClass(String name)
throws ClassNotFoundException {
try{
String c = name.replace('.', File.separatorChar) +".class";
URL u = ClassLoader.getSystemResource(c);
String classPath = ((String) u.getFile()).substring(1);
File f = new File(classPath);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte buff[] = new byte[(int) f.length()];
dis.readFully(buff);
dis.close();
return defineClass(name, buff, 0, buff.length, null);
} catch(Exception e){
throw new ClassNotFoundException(e.getMessage(), e);
}
}
};
Class<?> t = cl.loadClass("Test$Restartable");
Object[] args = new Object[] { new String[0] };
t.getMethod("main", new String[0].getClass()).invoke(null, args);
}
public static class Restartable {
private static final long argument = System.currentTimeMillis();
public static void main(String args[]) throws Exception {
System.out.println(argument);
}
}
}
how about this structure
public static void main(String... args) {
boolean restart = true;
while (restart )
{
retart = runApplication();
}
}
If you ever detect the need to restart you application, have runApplication return true.
If it is time to exit return false;
If you have an UI or a daemon so you can control output to stdout, you can make a wrapper on the outside that starts your program.
If the program upon exit outputs "RESTART" you can restart your program again from this wrapper. If not, it just ends.
Or if you want the pure java way, you can go with a solution with classloaders as Peter Lawrey mentioned in his post. Before going down this route you should really rethink your design (if it is your code) and make your code capable of cleaning itself up.

JUnit Exception Testing

Edit: Not JUnit 4 available at this time.
Hi there,
I have a question about "smart" exception testing with JUnit. At this time, I do it like this:
public void testGet() {
SoundFileManager sfm = new SoundFileManager();
// Test adding a sound file and then getting it by id and name.
try {
SoundFile addedFile = sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
SoundFile sf = sfm.getSoundfile(addedFile.getID());
assertTrue(sf!=null);
System.out.println(sf.toString());
sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
assertTrue(sf!=null);
System.out.println(sf.toString());
} catch (RapsManagerException e) {
System.out.println(e.getMessage());
}
// Test get with invalid id.
try {
sfm.getSoundfile(-100);
fail("Should have raised a RapsManagerException");
} catch (RapsManagerException e) {
System.out.println(e.getMessage());
}
// Test get by name with invalid name
try {
sfm.getSoundfileByName(new String());
fail("Should have raised a RapsManagerException");
} catch (RapsManagerException e) {
System.out.println(e.getMessage());
}
}
As you can see, I need one try/catch block for each function that is supposed to throw an exception. It seems not to be a good way to do this - or is there no possibility to reduce the use of try/catch?
I suggest that you need to break up testGet into multiple separate tests. The individual try/catch blocks seem to be pretty independent of each other. You may also want to extract the common initialization logic into its own setup method.
Once you have that, you can use JUnit4's exception annotation support, something like this:
public class MyTest {
private SoundManager sfm;
#Before
public void setup() {
sfm = new SoundFileManager();
}
#Test
public void getByIdAndName() {
// Test adding a sound file and then getting it by id and name.
SoundFile addedFile =
sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
SoundFile sf = sfm.getSoundfile(addedFile.getID());
assertTrue(sf!=null);
System.out.println(sf.toString());
sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
assertTrue(sf!=null);
System.out.println(sf.toString());
}
#Test(expected=RapsManagerException.class)
public void getByInvalidId() {
// Test get with invalid id.
sfm.getSoundfile(-100);
}
#Test(expected=RapsManagerException.class)
public void getByInvalidName() {
// Test get with invalid id.
sfm.getSoundfileByName(new String());
}
}
If you have an expected exception and you can't use an annotation to trap it, you need to catch it and assert that you've got what you expected. For example:
Throwable caught = null;
try {
somethingThatThrows();
} catch (Throwable t) {
caught = t;
}
assertNotNull(caught);
assertSame(FooException.class, caught.getClass());
If you can use an annotation instead, do that as it's much clearer. But that's not always possible (e.g., because you're testing a sequence of methods or because you're using JUnit 3).
With JUnit 4, you can use annotations instead. However, you should separate your test into 3 distinct methods for this to work cleanly. Note that IMHO catching an exception in the first scenario should be a failure, so I modified the catch block accordingly.
public void testGet() {
SoundFileManager sfm = new SoundFileManager();
// Test adding a sound file and then getting it by id and name.
try {
SoundFile addedFile = sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
SoundFile sf = sfm.getSoundfile(addedFile.getID());
assertTrue(sf!=null);
System.out.println(sf.toString());
sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
assertTrue(sf!=null);
System.out.println(sf.toString());
} catch (RapsManagerException e) {
fail(e.getMessage());
}
}
#Test(expected=RapsManagerException.class)
public void testGetWithInvalidId() {
SoundFileManager sfm = new SoundFileManager();
sfm.getSoundfile(-100);
}
#Test(expected=RapsManagerException.class)
public void testGetWithInvalidName() {
SoundFileManager sfm = new SoundFileManager();
sfm.getSoundfileByName(new String());
}
The most concise syntax is provided by catch-exception:
public void testGet() {
SoundFileManager sfm = new SoundFileManager();
... // setup sound file manager
verifyException(sfm, RapsManagerException.class)
.getSoundfile(-100);
verifyException(sfm, RapsManagerException.class)
.getSoundfileByName(new String());
}
In Java 8, you can use lambda expressions to get tighter control over when the exception is thrown. If you use the annotations method then you're only asserting that the exception is thrown somewhere in the test method. If you're executing more than one line of code in the test then you risk your test passing when it should fail. Java 8 solution is something like this.
static void <T extends Exception> expectException(Class<T> type, Runnable runnable) {
try {
runnable.run()
} catch (Exception ex) {
assertTrue(ex.getClass().equals(type));
return;
}
assertTrue(false);
}
Usage:
#Test
public void test()
MyClass foo = new MyClass();
// other setup code here ....
expectException(MyException.class, () -> foo.bar());
}

Simulating python's With statement in java

Is there something like Python with context manager in Java?
For example say I want to do something like the following:
getItem(itemID){
Connection c = C.getConnection();
c.open();
try{
Item i = c.query(itemID);
}catch(ALLBunchOfErrors){
c.close();
}
c.close();
return c;
}
where in python I just have:
with( C.getConnection().open() as c):
Item i = c.query(itemID);
return i;
Java 7 has introduced a new feature to address this issue: "try with resources"
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Close resource quietly using try-with-resources
The syntax is to place the resource in parentheses after the try keyword:
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
Prior to Java 7, you can use a finally block.
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Not at the moment; Java still hasn't added syntactic sugar for this pattern. Still, it won't get as clean as with(Python) or using(C#), but you can at least clean that up a little bit by just having one call to c.close() inside a finally block, instead of twice as you've done:
try {
// use c
} finally {
c.close()
}
This also brings it in line with how both with and using are actually implemented, which is a try..finally block (not a try..catch).
As tzaman said, the secret is using finally; generally:
Resource r = allocateResource();
try {
// use resource
}
finally {
r.dispose();
}
Things to note here:
try and finally each create a variable scope. So allocating your resource within the try clause won't work, as it won't be visible in the finally clause- you've got to declare the resource's variable before the try statement.
If you have several resources to allocate, the general pattern applies cleanly, but this is often not evident to beginners:
Resource1 r1 = allocateResource1();
try {
// code using r1, but which does not need r2
Resource r2 = allocateResource2();
try {
// code using r1 and r2
}
finally {
r2.dispose();
}
}
finally {
r1.dispose();
}
, and so on and so forth if you have more resources to allocate. If you have a couple of them, you will surely be tempted to try and avoid deep nesting of try... finally statements. Don't. You can get resource deallocation and exception handling right without nesting so many try... finally statements, but getting it right without nesting try... finally is even uglier than deep nesting.
If you frequently need to use a set of resources, you can implement a functor-based method to avoid the repetition, something like:
interface WithResources {
public void doStuff(Resource1 r1, Resource2 r2);
}
public static void doWithResources(WithResources withResources) {
Resource r1 = allocateResource1();
try {
Resource r2 = allocateResource2();
try {
withResources.doStuff(r1, r2);
}
finally {
r2.dispose();
}
}
finally {
r1.dispose();
}
}
Which then you can use like this:
doWithResources(new WithResources() {
public void doStuff(Resource1 r1, Resource2 r2) {
// code goes here
}
});
doWithResources will automatically handle allocation and deallocation correctly, and your code will have less repetition (which is a good thing). However:
Java's syntax for anonymous classes is excessively verbose
Checked exceptions within doStuff complicate things too much
, two points which I hope will be solved in Java 7.
You can find this kind of code throughout Spring, for instance:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/classic-spring.html#orm-hibernate-template ; doInHibernate thingy.
There's an alternative using a generic wrapper like this:
final _<Item> item = new _<Item>();
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
item._ = c._.query( itemId );
}
});
return item._;
NOTE: The Java way is the one you've just described. This other is just for "fun" and experimentation:
The _ is a generic wrapper and the with function is an utility class defined somewhere else as:
class WithUtil {
public static void with( ConnectionFactory factory,
_<Connection> c, Runnable block ) {
try {
c._ = factory.getConnection();
c._.open();
block.run();
} catch( Exception ioe ){
}finally{
if( c._ != null ) try {
c._.close();
} catch( IOException ioe ){}
}
}
}
In strict theory, you could re-use it to perform other stuff, like deleting an item:
public void deleteItem( final int itemId ) {
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
Item item = c._.query( itemId );
if( ! item.hasChildren() ) {
c._.delete( item );
}
}
});
}
or update it
public void update( final int itemId, String newName ) {
final _<Connection> c = new _<Connection>();
with( factory, c, new Runnable() {
public void run(){
Item item = c._.query( itemId );
item.setName( newName );
c._.update( item );
}
});
}
Without having to integrate the try/catch again.
Here's a full working demo that proofs the concept ( and doesn't do anything else )
try-with-resources was introduced in Java 7. Prior to that you had to use try-finally blocks. See documentation here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Categories