Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Referring Methods that Throw Exceptions in Java
Saliya Ekanayake
The ability to refer (pass) methods in Java 8 is a convenient feature, however, as a programmer you might face the situtaion where some code that seemingly follow the correct syntax to refer a method that throws an exception gives a compilation error of an
Unhandled Exception
, which doesn't go away by wrapping the call in a try/catch
or adding a throws
clause to the method signature. See the following code,import java.util.function.Function;
public class PassingMethodsThatThrowExceptions {
public static int addOne(String value) throws NotANumberException{
int v = 0;
try{
v = Integer.parseInt(value);
} catch (NumberFormatException e){
throw new NotANumberException();
}
return v+1;
}
public static void increment(Function<String,Integer> incrementer, String value){
System.out.println(incrementer.apply(value));
}
public static void main(String[] args) {
increment(PassingMethodsThatThrowExceptions::addOne, "10");
}
}
This is a simple code, which has
- an
addOne
function that takes in aString
value representing a number then adds1
to it and returns the result as anint
. - an
increment
function that simply takes a function, which can perform the increment and a value then apply the function to the value. - the
main
method that callsincrement
withaddOne
function and value"10"
Note.
addOne
function is declared to throw possible exception of type NotANumberException
(the type of exception is NOT important here).
This code will result in following compilation error,
Error: java: incompatible thrown types exceptions.NotANumberException in method reference
If you use an IDE such as IntelliJIDEA it'll show
Unhandled Exception: NotANumberException
for the increment
method call in main
and adding try/catch
will not work.
What's going wrong here? It's actually a mistake on your end.
The
increment
function expects a function that takes a String
and returns an int
, but you forgot to mention that this method may also throw an exception of type NotANumberException
.
The solution is to correct the type of
incrementer
parameter in increment
function.
Note. you'll need to write a new functional interface because you can't add
throws NotANumberException
to thejava.util.function.Function
interface that's used to define the type of incrementer
parameter here.
Here's the working solution in full.
public class PassingMethodsThatThrowExceptions {
public interface IncrementerSignature{
public int apply(String value) throws NotANumberException;
}
public static int addOne(String value) throws NotANumberException{
int v = 0;
try{
v = Integer.parseInt(value);
} catch (NumberFormatException e){
throw new NotANumberException();
}
return v+1;
}
public static void increment(IncrementerSignature incrementer, String value) throws NotANumberException {
System.out.println(incrementer.apply(value));
}
public static void main(String[] args) {
try {
increment(PassingMethodsThatThrowExceptions::addOne, "10");
} catch (NotANumberException e) {
e.printStackTrace();
}
}
}
Also, note this is
NOT
something to do with referring methods or Java 8 in general. You may face a similar situation even in a case where you implement a method of an interface and in the implementation you add the throws SomeException
to the signature. Here's a stackoverflow post you'd like to see on this.
Hope this helps!
Get PID from Java
Saliya Ekanayake
This may not be elegant, but it works !
public static String getPid() throws IOException {
byte[] bo = new byte[100];
String[] cmd = {"bash", "-c", "echo $PPID"};
Process p = Runtime.getRuntime().exec(cmd);
p.getInputStream().read(bo);
return new String(bo);
}
C# and Java Operators Thread Safety
Saliya Ekanayake
Java and C# both have compound assignment operators and the increment/decrement operators. For example see http://msdn.microsoft.com/en-us/library/6a71f45d.aspx for a list of C# operators and http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html for the Java version.
It seems these two step operations, i.e. x op= y, x++, x--, ++x, and --x, are NOT thread safe. It makes sense as these operations require reading the current value of the given variable and then updating it with the computed value. It is possible for threads to interleave between these operations resulting erroneous final values.
There are many ways to guarantee the atomicity in such cases including synchronized blocks, atomic data types such as Java AtomicInteger, and interlocked operations like in C#.
Here are some links that may help,
C# interlocked methods: http://msdn.microsoft.com/en-us/library/System.Threading.Interlocked_methods.aspx
Java atomic classes http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html
C# library to do threading similar to OpenMP like constructs http://msdn.microsoft.com/en-us/library/dd460717.aspx
A Java alternative OpenMP like parallel constructs https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Multicore+Software+Research+Project
It seems these two step operations, i.e. x op= y, x++, x--, ++x, and --x, are NOT thread safe. It makes sense as these operations require reading the current value of the given variable and then updating it with the computed value. It is possible for threads to interleave between these operations resulting erroneous final values.
There are many ways to guarantee the atomicity in such cases including synchronized blocks, atomic data types such as Java AtomicInteger, and interlocked operations like in C#.
Here are some links that may help,
C# interlocked methods: http://msdn.microsoft.com/en-us/library/System.Threading.Interlocked_methods.aspx
Java atomic classes http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html
C# library to do threading similar to OpenMP like constructs http://msdn.microsoft.com/en-us/library/dd460717.aspx
A Java alternative OpenMP like parallel constructs https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Multicore+Software+Research+Project
8:55 PM
C#
,
compound assignment operators
,
concurrency
,
java
,
thread safety
IntelliJIDEA: A Feature I Like to See
Saliya Ekanayake
Recently I was doing some tiresome debugging with Java using IntelliJIDEA. It was then that I thought that there is a great improvement we can do. This is totally my imagination, so I am not sure on any implementations in the Internet (yet).
The IDEA enables you to put debug points. These debug points may serve in creating a virtual path to traverse through the code. Thus, you are able to quickly jump to the next important point of code by just hitting F9. All this works really well for your debugging scenario. Now, what if you want to debug a different scenario, yet do not want to remove the older debug points? Then you have no option other than to add any new break points for the new scenario along with the older break points. This works okay, but makes the life bit hard since F9 will jump to points which are useless for the new scenario.
So what I suggest is to have a mechanism to define break points separately for each debugging scenario. So when you place a break point you can give it a scenario ID and inform the debugger to follow the break points for the relevant ID. It will be like layers that you find in Adobe Photoshop. You can on/off layers. Similarly we can deactivate a set of debug points based on their ID.
I wonder what JetBrains would think about this :)
The IDEA enables you to put debug points. These debug points may serve in creating a virtual path to traverse through the code. Thus, you are able to quickly jump to the next important point of code by just hitting F9. All this works really well for your debugging scenario. Now, what if you want to debug a different scenario, yet do not want to remove the older debug points? Then you have no option other than to add any new break points for the new scenario along with the older break points. This works okay, but makes the life bit hard since F9 will jump to points which are useless for the new scenario.
So what I suggest is to have a mechanism to define break points separately for each debugging scenario. So when you place a break point you can give it a scenario ID and inform the debugger to follow the break points for the relevant ID. It will be like layers that you find in Adobe Photoshop. You can on/off layers. Similarly we can deactivate a set of debug points based on their ID.
I wonder what JetBrains would think about this :)
Java Regex: Check for non word characters
Saliya Ekanayake
I wanted to test a given string to see if it contains any non word characters in Java. Initially I came up with a lengthy version ;) Then after a bit of search I could simply shorten it.
Version1: regular expression
"\\p{Alnum}*[~!@#$%^&*()\\+=\\-:;<>\\s?\\[\\]{},/\\\\\"]+\\p{Alnum}*"
Version2: regular expression
"\\p{Alnum}*\\W+\\p{Alnum}*"
Here's a nice guide (http://java.sun.com/docs/books/tutorial/essential/regex/index.html) to start with Java regular expressions
Version1: regular expression
"\\p{Alnum}*[~!@#$%^&*()\\+=\\-:;<>\\s?\\[\\]{},/\\\\\"]+\\p{Alnum}*"
Version2: regular expression
"\\p{Alnum}*\\W+\\p{Alnum}*"
Here's a nice guide (http://java.sun.com/docs/books/tutorial/essential/regex/index.html) to start with Java regular expressions
Java Strings: literal.equals(param) OR param.equals(literal)
Saliya Ekanayake
Comparing strings is bit tricky :) Say for an example you want to test a String reference against the literal "hello". In simple terms you have a String (say helloStr) and you want to see if the content of that is equals to "hello". You have two choices here,
1. helloStr.equals("hello")
2. "hello".equals(helloStr)
Both will do fine, but which is the better one? I've been using the second form but never thought of the difference (hmm, that's bad ;) anyway people do remember certain things bit later). In one of the code reviews at WSO2 it was revealed. The first form can lead to a Null pointer exception in the case when the helloStr is null. The second option will save you from this since the literal "hello" is not null always and you are invoking a method of a not null object. In this case even if the helloStr is actually null it doesn't matter because it'll only cause the program to check "hello" against null which results false.
If you are checking two String references then you have no option, but always try to invoke the equals() from the most probably not null reference.
Little things do matter :)
1. helloStr.equals("hello")
2. "hello".equals(helloStr)
Both will do fine, but which is the better one? I've been using the second form but never thought of the difference (hmm, that's bad ;) anyway people do remember certain things bit later). In one of the code reviews at WSO2 it was revealed. The first form can lead to a Null pointer exception in the case when the helloStr is null. The second option will save you from this since the literal "hello" is not null always and you are invoking a method of a not null object. In this case even if the helloStr is actually null it doesn't matter because it'll only cause the program to check "hello" against null which results false.
If you are checking two String references then you have no option, but always try to invoke the equals() from the most probably not null reference.
Little things do matter :)
Convert ByteArrayInputStream to String
Saliya Ekanayake
Recently one of my friends wanted to get the string contained in a ByteArrayInputStream in Java. The method do this was bit tricky and I thought it'd be nice to share it.
ByteArrayInputStream bais = // get your ByteArrayInputStream instance
int length = bais.available();
byte [] buff = new byte[length];
bais.read(buff);
That's it!!
ByteArrayInputStream bais = // get your ByteArrayInputStream instance
int length = bais.available();
byte [] buff = new byte[length];
bais.read(buff);
That's it!!
Saliya Ekanayake
Perceptron in Java
I'm following Neural Networks class for my final year and I felt it's a cool subject. I'm still a newbie in this field. But I gave a try to implement a simple perceptron to train few logic gates. It was a cool experience.
I'm following Neural Networks class for my final year and I felt it's a cool subject. I'm still a newbie in this field. But I gave a try to implement a simple perceptron to train few logic gates. It was a cool experience.
Java Threads - Simple Example
Saliya Ekanayake
public class MyThreadExtendingThread extends Thread{
public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 1 says - " + i);
}
}
}
public class MyThreadImplementingRunnable implements Runnable{
public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 2 says - " + i);
}
}
}
public class ThreadTester {
public static void main(String[] args) {
/* Ok think of a thread as a child in your class. You ask the child
to count from 0 to 100000. You as the teacher starts counting with the child.
But you two count on two different "threads" so you don't have to wait till
the kid is finish counting.
Let's see this in java - run and see
*/
//MyThreadExtendingThread extends java.lang.Thread class
MyThreadExtendingThread t1 = new MyThreadExtendingThread(); // create a kid to count
t1.start(); // ask the kid to start his job (in this case counting)
/*MyThreadImplementingRunnable implements java.lang.Runnable interface
so if you have to create an instance out of java.lang.Thread class
and pass an instance of your MyThreadImplementingRunnable to it. Then call start()
method of the java.lang.Thread instance
*/
Thread t2 = new Thread(new MyThreadImplementingRunnable()); // create another kid
t2.start(); // ask the kid to start his job (in this case counting)
// you also start counting
for(int i = 0; i < 100000; i++){
System.out.println("Teacher says - " + i);
}
}
}
public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 1 says - " + i);
}
}
}
public class MyThreadImplementingRunnable implements Runnable{
public void run(){
for(int i = 0; i < 100000; i++){
System.out.println("child 2 says - " + i);
}
}
}
public class ThreadTester {
public static void main(String[] args) {
/* Ok think of a thread as a child in your class. You ask the child
to count from 0 to 100000. You as the teacher starts counting with the child.
But you two count on two different "threads" so you don't have to wait till
the kid is finish counting.
Let's see this in java - run and see
*/
//MyThreadExtendingThread extends java.lang.Thread class
MyThreadExtendingThread t1 = new MyThreadExtendingThread(); // create a kid to count
t1.start(); // ask the kid to start his job (in this case counting)
/*MyThreadImplementingRunnable implements java.lang.Runnable interface
so if you have to create an instance out of java.lang.Thread class
and pass an instance of your MyThreadImplementingRunnable to it. Then call start()
method of the java.lang.Thread instance
*/
Thread t2 = new Thread(new MyThreadImplementingRunnable()); // create another kid
t2.start(); // ask the kid to start his job (in this case counting)
// you also start counting
for(int i = 0; i < 100000; i++){
System.out.println("Teacher says - " + i);
}
}
}
Subscribe to:
Posts
(
Atom
)