Using notifyAll()


package com.thread;

public class Reader extends Thread {
Calculator c;

public Reader(Calculator calc) {
c = calc;
}

public void run() {
synchronized(c) {
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {

}
System.out.println("Total is: " + c.total);
}
}

public static void main(String[] args) {
Calculator calculator = new Calculator();

// starts three threads that are all waiting to receive
// the finished calculation
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();

// start the calculator with its calculation
calculator.start();
}
}

class Calculator extends Thread {
int total;

public void run() {
synchronized(this) {
for(int i = 0; i < 100; i ++) {
total += i;
}
notifyAll();
}
}
}

How far will my salary go in another city?

Money magazine posts a cost of living web calculator that covers a whole lot of U.S. cities with fairly up-to-date data, giving you the lowdown on how far your salary would go in your dream city.

More likely, though, is that you’d want a comparison of the cities you’re looking at moving to for a new job or opportunity. Money’s calculator pulls data on the cost of health care, groceries, utilities, and other necessities from the last four quarters available from The Council for Community and Economic Research, whereas some Google-located city cost comparison sites are working with years-old data.

http://cgi.money.cnn.com/tools/costofliving/costofliving.html

Using threads and ProgressDialog

This is a simple tutorial to show how to create a thread to do some work while displaying an indeterminate ProgressDialog. Click here to download the full source.

We’ll calculate Pi to 800 digits while displaying the ProgressDialog. For the sake of this example I copied the “Pi” class from this site.

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.

Because this Activity is so small I’ll show you the whole thing and then discuss it at the end:


package com.helloandroid.android.progressdialogexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

public class ProgressDialogExample extends Activity implements Runnable {

private static String TAG = "ProgressDialogExample";
private String pi_string;
private TextView tv;
private ProgressDialog pd;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

tv = (TextView) this.findViewById(R.id.main);
tv.setText("Press any key to start calculation");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true, false);

Log.i(TAG, "Thread.currentThread().getName(): " + Thread.currentThread().getName());

// create a new thread using the current class as the runnable object
// new ProgressDialogExample() passed to Thread constructor
Thread thread = new Thread(this);
thread.start();

Log.i(TAG, "thread.getName(): " + thread.getName());

return super.onKeyDown(keyCode, event);
}

public void run() {
Log.i(TAG, "Thread.currentThread().getName(): " + Thread.currentThread().getName());

pi_string = Pi.computePi(800).toString();

Log.i(TAG, "run()");

handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);
}
};

}

So we see that this Activity implements Runnable. This will allow us to create a run() function to create a thread.

In the onCreate() function on line 18 we find and initialize our TextView and set the text telling the user to press any key to start the computation.

When the user presses a key it will bring us to the onKeyDown() function on line 27. Here we create the ProgressDialog using the static ProgressDialog.show() function, and as a result the pd variable is initialized. We also create a new Thread using the current class as the Runnable object. When we run thread.start() a new thread will spawn and start executing the run() function.

In the run() function we calculate pi and save it to the String pi_string. Then we send an empty message to our Handler object on line 40.

Why use a Handler?
We must use a Handler object because we cannot update most UI objects while in a separate thread. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.

When our Handler receives the message we can dismiss our ProgressDialog and update the TextView with the value of pi we calculated. It’s that easy!

http://www.helloandroid.com/node/243

Callback

Java does not have procedure variables to implement function pointer callbacks the way C/C++ does. A callback would be used in C for example to pass a sin or cos function to generic plotting program. Callbacks are a way of passing functions as parameters. The callee can call the function passed to it as a parameter as often as it wants, with whatever parameters it wants.

Why would you want a callback? The normal parameter passing mechanism lets caller provide the callee with information, but provides only meager flow of information in the reverse direction, the single returned result primitive or Object. Further the callee cannot provide further information back to the caller once it has returned. The callback mechanism allows a two-way flow of information and exchange of computing resources between caller and callee.

Consider a component consisting of a panel of buttons. The caller wants to control the labellings on the buttons, how they are rendered etc. The callee wants to notify the caller whenever one of the buttons was pressed, and which one. The callback mechanism, sometimes called a Listener mechanism, allows the callee to notify the caller, the listener, of interesting events, or to use some of the methods the caller has access to.

There are four basic techniques to fake a callback function in Java.

  1. Subclassing. Subclass the calling class with an overridden callback method. Pass “this ” as a parameter.
  2. Delegation via subclassing. Pass a subclassed Callback delegate object that knows how to invoke the callback method(s).
  3. Pass a Callback delegate object that implements an interface for the callback method(s).
    HeapSort: source code for an example of the delegate technique

    This is how it is most commonly done. It offers most flexibility,

  4. Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it
    as a parameter all in one line. This technique with EventListeners tends to muddle GUI and
    program logic making your GUI code non-reusable. Unless the anonymous inner classes are simple, it is generally wiser to
    make them ordinary free-standing named classes.

If you don’t already understand delegates, that probably sounds like Greek. Just look at the HeapSort example. Once you understand that code, you will easily understand the other three variants. It is much simpler than it first sounds.

Callback has a totaly different meaning in the context of security. For secure login you call the server. It then calls you back. This makes it harder for you to spoof being someone else. This may be done over phone lines or over the Internet. It is the same scheme a jealous husband might use to ensure his wife is really home as she claims.

http://mindprod.com/jgloss/callback.html

Unescape HTML special characters from a String

import java.util.*; public class StringUtils { private StringUtils() {} private static HashMap htmlEntities; static { htmlEntities = new HashMap(); htmlEntities.put(“<","”,”>”); htmlEntities.put(“&”,”&”) ; htmlEntities.put(“””,”\””); htmlEntities.put(“à”,”a”); htmlEntities.put(“À”,”A”); htmlEntities.put(“â”,”a”) ; htmlEntities.put(“ä”,”a”); htmlEntities.put(“Ä”,”A”) ; htmlEntities.put(“”,”A”); htmlEntities.put(“å”,”a”) ; htmlEntities.put(“Å”,”A”); htmlEntities.put(“æ”,”æ”) ; htmlEntities.put(“Æ”,”Æ” ); htmlEntities.put(“ç”,”c”); htmlEntities.put(“Ç”,”C”); htmlEntities.put(“é”,”e”); htmlEntities.put(“É”,”E” ); htmlEntities.put(“è”,”e”); htmlEntities.put(“È”,”E”); htmlEntities.put(“ê”,”e”) ; htmlEntities.put(“Ê”,”E”); htmlEntities.put(“ë”,”e”) ; htmlEntities.put(“Ë”,”E”); htmlEntities.put(“ï”,”i”) ; htmlEntities.put(“Ï”,”I”); htmlEntities.put(“ô”,”o”) ; htmlEntities.put(“Ô”,”O”); htmlEntities.put(“ö”,”o”) ; htmlEntities.put(“Ö”,”O”); htmlEntities.put(“ø”,”ø”) ; htmlEntities.put(“Ø”,”Ø”); htmlEntities.put(“ß”,”ß”) ; htmlEntities.put(“ù”,”u”); htmlEntities.put(“Ù”,”U”); htmlEntities.put(“û”,”u”); htmlEntities.put(“Û”,”U”) ; htmlEntities.put(“ü”,”u”); htmlEntities.put(“Ü”,”U”) ; htmlEntities.put(” “,” “); htmlEntities.put(“©”,”\u00a9″); htmlEntities.put(“®”,”\u00ae”); htmlEntities.put(“€”,”\u20a0″); } public static final String unescapeHTML(String source, int start){ int i,j; i = source.indexOf(“&”, start); if (i > -1) { j = source.indexOf(“;” ,i); if (j > i) { String entityToLookFor = source.substring(i , j + 1); String value = (String)htmlEntities.get(entityToLookFor); if (value != null) { source = new StringBuffer().append(source.substring(0 , i)) .append(value) .append(source.substring(j + 1)) .toString(); return unescapeHTML(source, i + 1); // recursive call } } } return source; } public static void main(String args[]) throws Exception { // to see accented character to the console java.io.PrintStream ps = new java.io.PrintStream(System.out, true, “Cp850”); String test = “© 2007 Réal Gagnon “; ps.println(test + “\n–>\n” +unescapeHTML(test, 0)); /* output : © 2007 Réal Gagnon –> ⓒ 2007 Real Gagnon */ } } http://www.rgagnon.com/javadetails/java-0307.html

5 great freelance sites for developers

The following are five great websites that I have found for freelance work. This is for mostly programming/development, which includes PHP and many other languages.

1) http://www.rentacoder.com

Rentacoder is good place to find small to mid-sized projects for earning extra money. It also offers a rating system which can hurt or help you depending on your work.

2) http://odesk.com/

Odesk is a little bit different than the rest of the sites listed here. Instead of bidding on projects, you bid on hours. Employers can list the amount of hours/week and # of weeks they need out of a potential freelancer.

3) http://www.craigslist.com

Craigslist is great because there is no barrier to entry for either the employer or the potential freelancer/employee (it is also among the top sites on the Internet). This can also be a detriment because anyone with a computer can post a job listing.

4) http://programmermeetdesigner.com/

A unique website that provides an opportunity for programmers to meet and work with designers.

5) http://www.guru.com

Guru.com is a clean and professional website that has lots of large-scale projects. It also has a fairly high barrier to entry for the employers, which usually means better paying jobs.

http://www.rawseo.com/news/2009/06/04/5-great-freelance-sites-for-developers/