Java’s sleep(), suspend(), and resume()

As we all know, the very useful Java Thread methods sleep(), suspend(), and resume() have been deprecated. Many articles online tell us to use a control variable instead, by polling the status of the variable at key points in the run() method. This may be a good idea, but I felt that we could have done better. For example, thread synchronization: what happens if all you need to do is wait for a particular signal to continue? There’s really no point in awakening the thread every x milliseconds just to find out that it should still be sleeping. Just as an analogy: Would you like to wake up every hour to check your email?

Solution: the wait() and notify() methods in a Thread class. To understand why they are named this way, you must first understand the role of locks (aka mutex/semaphore) in thread synchronization. I assume you have a basic understanding of what locks are.

Locks in Java are pretty simple, and you only need to know the synchronized keyword. Each object in Java is its own lock, so you may lock on any variable or object that you have a reference to. If you’re going to use thread synchronization, then it’s most likely that the thread in charge of notify() has is a reference to the other thread. So the waiting thread should put a lock on itself. In terms of code:

// put this code in the thread that should be waiting
synchronized (this) {
  wait();
}

You can also set a timeout to wait using wait(int n) so that it continues after that time, regardless of whether it was notify()-ed. This can be a good substitute for sleep(int n) too, if you didn't implement notify() anywhere else :P

Here's the example code to set you going.

public class TestThreadWait {
  public static void main(String[] args) {
    final WaitThread w = new WaitThread();
    w.start();


    final Timer t = new Timer();
    TimerTask tt = new TimerTask() {
      public void run() {
        synchronized (w) {
          w.notify();
        }
        t.cancel();
      }
    };
    t.schedule(tt, 5000);
  }
}


class WaitThread extends Thread {
  public void run() {
    System.out.println("Entering wait, should wake in 5s..");
    synchronized (this) {
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Out of wait!");
  }
}

Posted in Computing | Tagged , | Leave a comment

http Keepalive

I was making a client program that connects to my server online a few days ago. Then I wondered about the kind of connection I needed to make with my server. It was a problem because:

  1. I cannot run external applications on the server (this is a shared host). Therefore, I wanted to use individual php scripts backed by a MySQL server to serve all the functions through a http connection.
  2. Certain aspects of the program was passive, and required just listening to the server for data. It is unknown how long the connection needs to last, but would normally last around 15 mins. It would be pretty safe if I could get a connection that stays alive for at least 30 mins.

Since the problem of which port to use was determined by my first requirement, I needed to find out whether a http connection performs the same as other kinds of connections to other ports. Theoretically, there would be no need to do this, because a port 80 connection should be no different from other ports. But port 80 is managed by web servers (eg. Apache, IIS), which impose their own sort of rules. One of which I’m aware of is that connections that are idle for more than x minutes will be forcefully terminated by the server. Such a thread should be assumed dead by web server standards, since a webpage should theoretically stream data continually (in the case of downloading a massive file) or close itself (since the required data has all been streamed out). Another restriction I know possible on Apache servers is the ability to close any connection that has been alive for more than y minutes, regardless of whether it is in idle. This is because Apache has a fixed number of threads it can use to serve pages, and it has to have a way to say when a thread should likely be no longer in use.

The first problem will force me to stream data (whether real or bogus) regularly down the connection in order to keep it alive. We don’t want to force useless data through the pipe too often, because that will increase bandwidth usage for nothing. The second problem will determine whether I can actually use http to stream my data down without needing to constantly reconnect.

I made a simple php script that uses GET to get a start and end count, with a stepsize. Using these parameters, I sleep the script in a for loop from start seconds to end seconds, each time adding a step of stepsize. Stepsize will determine your accuracy, and start and end is the range of numbers you’re guessing the connection will timeout after. I used 30s accuracy, and found that my webhost terminates an idle connection after 5 minutes.

For the 2nd part, I made another script that takes a sleep time, and number of iterations it should go through before ending the script. I used 5 minutes for sleep time, and put it for 180 iterations (15hrs total). I really wanted to test up to 10hrs, but put 15 for fun :P The script ran for 132 iterations before I stopped it (time to sleep!). That’s a grand total of 11h!

I assume that it will run forever since it has already run for 11h. This should likely be okay.. since a normal webpage has a serve time in seconds or milliseconds, 11 hours would certainly seem like eternity.

Actually, the results for the 2nd part makes sense. A connection is only dead if either side (server or client) can no longer receive and send data. As long as data is sent and replies are heard on both ends, this means that both sides have still kept the connection open. How can such a connection be considered dead?

I would also like to note that my results are subjective. Different web servers have different settings, so it is important not to rely on just my results if you have the need to use a long http connection like me. In future, I would also like to test this on the major cloud providers (AWS, Google Cloud. Azure is out cos I need to pay, unless someone is willing to host my script and let me do my little experiment :P ). They may have interesting restrictions too.

Posted in Computing | Tagged , , | Leave a comment

A simple way to Java “friends”

Problem: Implement selective exposure of fields and methods in a class. For example, Class A can call M.x(), but Class B should not be allowed to. However, Class A, B, and M do not have subclass-superclass relations nor composition relations, so you cannot do Class A extends M and set x() to protected.

A solution to this problem is useful because:

  1. In the MVC architecture, the UI should retrieve its data from the Model components directly. This means that your UI only needs read-access to your data. However, the Controller system needs to both read and modify your data. Using this solution, you can expose the “getters” as public functions, but selectively expose the “setters” and other methods to only the Controller system. The M/V/C correspond to Classes M/B/A in the problem stated above.
  2. API-exposure. The selective exposure happens because you only wish to expose a select few of the public methods that you have written. The rest of the methods are public because you need to use them internally across classes, but they shouldn’t be used by clients using your API. Here, Class M is your data, Class A is your “internal public” class, and Class B is implemented by a client using your API library.

This is pretty obvious to C++ folks – use the friend keyword. But Java is a loner, and it doesn’t like friends :( So how?

A quick google for “Java friend” gives us a few options:

  1. Interface segregation. Implement 2 interfaces on your data objects, give both references to the Controller but only read-interface to UI. This is easy and straightforward, but I like to use Singleton-like structures so that I don’t have to maintain references to data components everywhere.
  2. Java Reflections. This is by far the most secure method I found, but you gotta contend with Java’s SecurityManager, which will throw you Exceptions faster than you can catch. Also, the amount of code you have to write just to maintain these Reflections makes it unfeasible for anything other than large-scale projects.
  3. I personally like this one the best – play around with visibility. Java has 4 levels of visibility (public, protected, package, private). It turns out that the package level visibility, while not taught in classes, is actually a very useful concept! I will explain this one in more detail.

Java’s package level visibility provided for exactly what I needed, because it so happens that the 3 Classes A, B, and M I described above usually resides in 3 different package/subpackages.

This is the code sample that I wrote that shows how I did selective exposure of methods.

Class M is found in package p1: it stores variables x and y, and provides accessors for them so anyone can read the data.

package friends.p1;

public class M {
   protected int x;
   protected int y;
   public M(int x, int y) {
      this.x = x;
      this.y = y;
   }

   public int getX() { return x; }
   public int getY() { return y; }
}

Class A, which uses Class M, is found in package p2: it extends from Class M and has package-level visibility. It provides its own mutators so that other classes in the same package p2 can use them, but anyone outside p2 cannot use them.

package friends.p2;
import friends.p1.M;

class A extends M {
   public A(int x, int y) {
      super(x, y);
   }

   public void setX(int x) { this.x = x; }
   public void setY(int y) { this.y = y; }
}

Class B is the class attempting to use A’s mutator methods. However, as B is in a different package, it will not be able to do so.

package friends.p3;
import friends.p1.M;
import friends.p2.A; // error

public class B {
   public B() {
      // Can't create object of A because it has package level visibility
      A a = new A(1, 2);
      // You can however create B and use the getters
      M m = new M(1, 2);
   }
}

Posted in Computing | Tagged , | Leave a comment

Mapping the Galactic Warp

Digging this back out from my archives! This is a very interesting project done when I was at Berkeley, where I took tons of astronomy classes (because they aren’t available in Singapore). In this lab, our team made use of a 4.5m radio telescope owned by UC Berkeley to map out the warp of the Galaxy.

In summary, our galaxy is not a flat spinning top, as most of the pictures show it to be. The arms of the galaxy actually have a little “tilt” in them with respect to the galactic plane, which means parts of it lie above the plane, and parts of it below the plane! Using the data we gathered from the radio telescope, I rendered a graphical representation of the galactic warp. The image is a little fuzzy, I hope to improve on my code in future and render a nicer looking image!

Posted in Astro | Tagged , | Leave a comment

Virtually Smart Campus

My team (James Yong, Caleb Chao, Yee Jia Hao, and me) worked on this project over the period of 1 semester, as our class project for the module Mobile and Multimedia Networking. This project made use of the Coalition Framework (a Context-awareness framework) and is written for the Android platform.

Virtually Smart!
The application was so named because it allows users to share information quickly, ordered by location and the time the information was posted. Users also show their positions on the map, so you can see where your friends are currently located using this map (similar to Google Latitude).

Each piece of information is represented as a data point on a map of the area, which you can select to view more information about it. For example, we have integrated the School’s printer queue data into the system, and users can view the current print queue on each printer in an area and choose the one they want to use.

The application is “smart” because new services can be plugged into the system with ease, as each service is modularized and served using the SOA architecture we have created for the application. A real-life use case could be the school crowd-sourcing the problem of finding spoilt stuff around the school. If a student spots a spoilt chair in a classroom, he can create a data point at the position on the map, and title it “Spoilt chair”. A service monitors and picks up this new data point, sends it to the maintenance department, which can then dispatch a crew to fix up the issue.

User-friendly and clean UI
When the application starts, it immediately shows the area where the user is located. This makes it easy for him to find out what is happening around him. Features like panning and zooming the map are also coded into the UI, which make it similar to Google Maps (except it shows the Campus map instead).

Fingerprinting for accurate Localization
The application uses the fingerprinting method to localize the user on a map of our School of Computing, by scanning the delta RSSI of pairs of APs in the area. The accuracy of this localization method depends on the number of APs around the area, and in our case, it is able to achieve ~10m accuracy. It also has the ability to detect which floor of the building you are on, as the delta RSSI is different even at the same spot on different floors.

Tracking user movements
The application is also able to track user movement on the map. The users’ positions are refreshed regularly. Because the difference in user position may be due to either the user moving or WiFi inaccuracy, we used an averaging formula to determine the user’s real location. The averaging formula also has the effect of reducing location jitter due to WiFi inaccuracy when the user is stationary.

Data points
Currently, the data points are allowed to be either text, pictures, or videos. More data types can be added in future.

Posted in Computing | Tagged , , | Leave a comment