Java JMF – Load and Play Media File

import javax.media.*;
import java.io.File;
import java.awt.*;

public class TrivialJMFPlayer extends Frame {

	public static void main (String[] args) {
		try {
			Frame f = new TrivialJMFPlayer();
			f.pack();
			f.setVisible (true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public TrivialJMFPlayer()
			throws java.io.IOException,
			java.net.MalformedURLException,
			javax.media.MediaException {

		FileDialog fd = new FileDialog
				(this, "TrivialJMFPlayer", FileDialog.LOAD);
		fd.setVisible(true);

		File f = new File(fd.getDirectory(), fd.getFile());

		Player p = Manager.createRealizedPlayer
				(f.toURI().toURL());
		Component c = p.getVisualComponent();
		add(c);

		p.start();
	}

}

Java – Synchronized HashMap Example

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.

Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.

Map map = Collections.synchronizedMap(new HashMap());
...
// This doesn't need to be in synchronized block
Set set = map.keySet();
// Synchronizing on map, not on set
synchronized (map) {
    // Iterator must be in synchronized block
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
        ...
    }
}

Java – Calculate Difference Between Two Dates Using Joda Time

Take a look @ Joda-Time FAQ

You can use a PeriodFormatter to get the format of your choice.

Try the following sample code.

DateTime dt = new DateTime();

DateTime twoHoursLater = dt.plusHours(2).plusMinutes(10).plusSeconds(5);

Period period = new Period(dt, twoHoursLater);

PeriodFormatter HHMMSSFormater = new PeriodFormatterBuilder()
        .printZeroAlways()
        .minimumPrintedDigits(2)
        .appendHours().appendSeparator("-")
        .appendMinutes().appendSeparator("-")
        .appendSeconds();
        .toFormatter(); // produce thread-safe formatter

System.out.println(HHMMSSFormater.print(period));

Page 2 of 4912345...102030...Last »