0 comments on “Using BitmapShader in Android”

Using BitmapShader in Android

Recently I had to implement some custom UI controls for one of our customers, and some of these controls involved drawing Bitmaps with rounded corners.
Android provides a handy approach to this problem, all the magic can be done with a little help from a class named BitmapShader.

With BitmapShader you can draw bitmaps in any shape and even more, here’s an example:

bitmap-shader-01

What BitmapShaderdoes is basically providing a pixel source to a Paint object, when you draw something on a Canvasyou have to specify the Paintinstance that will be used to paint your stuff, if that Paintis bound to a BitmapShader you’ll get your stuff painted using the Bitmap that the BitmapShaderwas created with.

Here’s how to create a BitmapShaderobject:

With the BitmapShaderin place you can now draw anything you want using a Paint which is bound to the shader, the binding can be achieved with the setShader() method of the Paint class:

Now everything is in place and you can start drawing your bitmaps, following is a list of what I did in the example screenshot above and the code I used to achieve each sample, also note that in order to draw on a Canvas I created a custom View subclass and I added the drawing code inside the onDraw() method, in a real scenario however try to avoid allocating stuff inside the onDraw() method.

Rounded corners

all-rounded


Bottom corners rounded

bottom-rounded


Top corners rounded

top-rounded


Circle

circle


Narrow oval

oval-narrow


Wide oval

oval-wide


Advertisements
0 comments on “Never synchronize on Java boxed primitives”

Never synchronize on Java boxed primitives

This is another pitfall that can easily compromise a whole application if not understood, it involves thread safety, Java objects immutability and boxed primitives.
Standard Java classes like Integer and Long are immutable. A class is said to be immutable if it is implemented in such a way that it’s value cannot be changed once the class has been instantiated.

Integer value = 10;

The Integer object declared above is immutable, it’s value can not be changed.
But wait a second, you say, what if I do this?

value++;

Oh, I say, you changed the object’s value with the increment operator!
Actually this is not what happened, when it comes to running this code the statement above is pretty much equivalent to this one:

value = new Integer(value + 1);

Since this class is immutable, as soon as you change it’s value a new Integer instance with the new value is created and assigned to value. This is what we call immutability and applies also to String, Boolean, Long, Double, BigInteger and so on. This is the first step in understanding what follows.
The second step is understanding boxed primitives, but you may already know what they are.

Boxed primitives can be really useful sometimes, and can be very tricky too. You can use them to represent values such as Integer, Long, Boolean, Double and so on. They are called boxed primitives, or wrapped primitives, because they wrap a primitive Java type such as int and long inside a class allowing a more flexible approach to a strong object oriented environment such as Java.

If you work in a multi threading environment you’ll often need to synchronize parts of your code to make sure that no thread except yours operates on an object that you are working on. Let’s say you have an Integer value that can be incremented by one thread and decremented by another thread, your code may look like this:

private Integer value = 0;
...
synchronized(value) {
  ...				
  value++;
  ...
}

But this innocent looking piece of code hides an horrible monster, can you spot it?
The synchronized block is synchronized against the value object which will no more be itself as soon as we increment it, let’s see it under a different light using what we learned about immutability:

private Integer value = 0;
...
synchronized(value) {
  ...				
  value = new Integer(value + 1);
  ...
}

The synchronized block works by locking the object on which we want to synchronize, but the object will change inside the block! The value reference will point to another Integer object after the increment!
The new Integer object with value 11 won’t be locked and as a result if some other thread tries to synchronize on the value object after our increment operation it will succeed.
As a result we’ll have two or more threads running at the same time even if they are supposed to be waiting to execute critical code sections one at a time.
This is dangerous as hell, this is the kind of bug that starts showing up on release day..

0 comments on “How not to compare Strings in Java”

How not to compare Strings in Java

In my previous post I wrote about how not to compare Integer and Long objects in Java in order to avoid undefined behaviours in your code caused by the Java interning mechanism. If not well understood interning can lead to catastrophic failures. You may think that your code is working fine while in fact it is not working at all.

Interning is used for String objects too so it’s important to know how the Java virtual machine can fool you. Let’s have a look at this code:

public static void main(String[] args) {
		
  String a = "test01";
  String b = "test01";
		
  System.out.println("Comparing \"" + a + "\" and " + "\"" + b + "\"");

  if (a == b) System.out.println("Matches");
  else System.out.println("Doesn't match");
		
}

Every Java developer knows that String objects cannot be compared with the == operator, because it only compares object instances and not objects values, the equals() method must be used instead. The code above creates two different String objects with the same value and then compares them with the == operator, thus the comparison should fail even if the values are the same.
However if you run it you’ll notice that it works perfectly, the output is:

Comparing "test01" and "test01"
Matches

This is the tricky part. You may now be fooled into believing that your code works fine while in fact it does not.

Interning is at work here, just like for Integers and Longs in the previous post. In Java all literal strings and string-valued constant expressions are interned. This means that both a and b in the code above are referencing the same instance of String that was created and interned when a was created with a literal value.

String a = "test01";
/** A String instance with value "test01" is now interned */

The code above will stop working as soon as it gets a little more complex:

public static void main(String[] args) {
		
  String a = "test01";
  String b = "test";
		
  b += "01";
		
  System.out.println("Comparing \"" + a + "\" and " + "\"" + b + "\"");
  if (a == b) System.out.println("Matches");
  else System.out.println("Doesn't match");
		
}

This time two String instances with values “test01” and “test” are interned, and when we append “01” to b a completely new String object is created (because of objects immutability) with value “test01” which will not refer to the interned one with the same value.
The output now is:

Comparing "test01" and "test01"
Doesn't match

Always use the equals() method to compare objects values in Java.

2 comments on “Java Long and Integer objects, Interning and comparison methods”

Java Long and Integer objects, Interning and comparison methods

This is someting that shocked me about Java, if you keep reading you’ll be shocked too.
The question is simple: how do you compare two Integers? And two Longs?
If you are a decent java developer you’d never do it like this:

Integer a = 1;
Integer b = 1;

if (a == b) /** Do some shit */

If you are wondering why, please stop reading this and never come back.

Any good java tutorial/book/teacher will prevent you from doing the above because of the behaviour of the java == operator which only compares object instances and not objects values. Since a and b are different instances of the Integer class the code above will not work. You must always use the equals() method to compare objects values in Java.

So far so good right?
Nope. The code above works like a charm. The if block is executed. That’s weird.

But wait there’s more, let’s now try something different:

Integer a = 1000;
Integer b = 1000;

if (a == b) /** Do some shit */

If you run this code you’ll notice that this time the if block is not executed. Weird.

So why this code behaves in a different way just by changing the values of a and b?
Very simple, once you know the secret.

The secret is called interning, it is a perverted mechanism used by the Java Virtual Machine to optimize code execution by keeping some frequently used instances ready to be used by your code. What happens is that Integer and Long instances with values ranging from -128 to 127 (range can be different depending on the specific JVM implementation) are created and stored permanently, or interned, by the Java Virtual Machine.
So when you create an Integer instance by assigning a value between -128 and 127 the JVM does not create a new Integer instance, it simply takes the Integer reference you declared and points it to it’s interned instance.
If you create two or more instances of the Integer class with values inside the interning range and then try to compare them using the == operator it will work, simply because you are comparing two Integer references that are referring to the same interned instance. Now you know the secret.

Note that the interning mechanism does not apply if we explicitly create two instances of the Integer class using the new operator:

Integer a = new Integer(1);
Integer b = new Integer(1);

if (a == b) /** Do some shit */

This code works as expected, the == operator does not work.

This interning stuff is an extremely dangerous mechanism that can possibly trick you into believing that the Java == operator works on Integers and Longs as well as with primitives int and long. It will work until your values are inside the interning range, once values being compared fall outside of the interning range.. well.. may the Force be with you.