Πέμπτη 27 Οκτωβρίου 2011

Concurrency in Java 6

Threads are lightweight processes that share the same memory space. A scheduler can swap between threads. Java uses preemptive multithreading, where the OS is responsible for swapping threads.
Java 5 has introduced a significant new paradigm to handle threads, compared to the primitive concurrent commands of pre version 5. It is recommended that you use the new java.util.concurrent.* package. In the following I show the thread commands for Java pre-version 5 and post-version 5.

Java 1-4 Java 5-7
Thread Creation
public class
MyThread extends Thread {
   public void run() {
     // your concurrent task here
   }
}

MyThread thread = new MyThread();
thread.start();

or

public class MyTask implements Runnable {
   public void run() {
     // your concurrent task here
   }
}

Thread thread = new Thread(new MyTask());

thread.start();

public class MyTask implements Runnable {
   public void run(){
     // your concurrent task here
   }
}
// Creates new threads as needed and destroys old threads
ExecutorService exec = Executors.newCachedThreadPool();
// Keeps a permanent total number of threads
ExecutorService exec = Executors.newFixedThreadPool(5);
// Like newFixedThreadPool but only for one thread
ExecutorService exec = Executors.newSingleThreadExecutor();
// To be scheduled, to replace java.util.Timer
ExecutorService exec = Executors.newScheduledThreadPool();
// Like before but for one thread only
ExecutorService exec = Executors.newSingleThreadScheduledExecutor();

exec.execute(new MyTask());
exec.shutdown();


int processors =
Runtime.getRuntime().availableProcessors();

ExecutorService executor = Executors.newFixedThreadPool(processors);

Future<Integer> futureResult = executor.submit(
   new Callable<Integer>() {
     public Integer call() {
       // long running computation that
       // returns an integer
     }
   });
Integer result = futureResult.get();
// block until result is ready
exec.shutdown();
Critical sections
public synchronized void method() {
  // same as synchronising on "this"
  // which is dangerous as another 
  // thread could get hold of "this"
  // and block your code.
  // When the lock is acquired for
  // the synchronized block, other
  // synchronized methods and
  // critical sections in the object
  // cannot be called.
}

// use this instead
// In Java, every object contains a “monitor”
// that can be used to provide
// mutual exlusion access to critical sections of code.

private final Object monitor = new Object();

public void method() {
  synchronized(monitor) {
    // your critical section here
  }
}

import java.util.concurrent.locks.*;

private final Lock lock = new ReentrantLock();

public void method() {     
  // cannot be interrupted
  lock.lock();
  // can be interrupted
  // lock.lockInterruptibly();
  try{
    // your critical section here
  } finally {
    lock.unlock();
  }
}

// can try lock
public void method() {
  boolean locked = lock.tryLock();
  if (locked) {
    try{
      // your critical section here
    } finally {
      lock.unlock();
    }
  } else {
    // do something else
  }
}


import java.util.concurrent.locks.*;

private final ReadWriteLock lock = new ReentrantReadWriteLock();

public void doWrite() {
   lock.writeLock().lock();
   try {
     // your critical section here
   } finally {
     lock.writeLock().unlock();
   }
}

public void doRead() {
   lock.readLock().lock();
   try {
      // your critical section here
   } finally {
      lock.readLock().unlock();
   }
}
Thread interactions


private final Object lock = new Object();  // must lock on the
same object

private volatile boolean notified = false;

public void doWait() {
  synchronized(lock) {
   while(!notified) {  // avoid spurious wakeups
    try {
      // releases the object lock and waits
      // until it gets notified
      // otherwise the notifying thread could
      // never acquire the lock!
      lock.wait();
    } catch(InterruptedException e) {
    }
   }

   //clear signal for next waiting thread and continue running
   notified = false;
  }
}

public void doNotify() {
  synchronized(lock) {
    notified = true;
    // sends a message to a thread waiting on the object lock
    lock.notify();
    // sends a message to all the threads waiting on the object lock
    // lock.notifyAll();
  }
}
import java.util.concurrent.locks.*;

private final Lock lock = new ReentrantLock();

private final Condition condition = lock.newCondition();

private volatile boolean notified = false;

public void doWait() {     
  lock.lock();
  try{
   while(!notified) {
    condition.await(); // like wait(), releases              
// the lock and suspends current thread
   }
  } finally {
    lock.unlock();
  }
  notified = false;
}

public void doNotify() {     
  lock.lock();
  try{
    notified = true;
    condition.signal();       // like notify()
    // condition.signalAll(); // like notifyAll()
  } finally {
    lock.unlock();
  }
}

final CountDownLatch latch = new CountDownLatch(3);
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(new Runnable() {
  public void run() {
    try { // puts it into WAITING state
      latch.await();  // until latch == 0
    } catch (InterruptedException e) {
      Thread.currentThread.interrupt();
      return;
    }
  }
});
for (int i=0; i<3; i++) {
  Thread.sleep(1000);
  latch.countDown(); // --latch;
}

final Semaphore semaphore = new Semaphore(3);
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(new Runnable() {
  public void run() {
    try {
      semaphore.acquire();
      try { 
        Thread.sleep(1000);
      } finally {
        semaphore.release();
      }
    } catch (InterruptedException e) {
      Thread.currentThread.interrupt();
      return;
    }
  }
});
Also check: CyclicBarrier, Semaphore, Exchanger

Atomicity/Visibility
/* The volatile modifier can be used to mark a field and indicate that changes to that field must be seen by all subsequent reads by other threads, regardless of synchronization.*/
public class MyClass implements Runnable {

private volatile boolean finished = false;

   public void finish() {
     finished = true;
   }

   public void run() {
     while(!finished) {
        // .. do processing
     }
   }
}
import java.util.concurrent.atomic.*;

public class Counter {
  private AtomicInteger value = new AtomicInteger();

  public int next() {
   return value.incrementAndGet();
 }
}

java.util.concurrent.atomic package:
  • AtomicBoolean 
  • AtomicLong 
  • AtomicInteger
  • AtomicReference 

Periodic Tasks
try {
  Thread.sleep(1000);
// or TimeUnit.SECONDS.sleep(1);
} catch(InterruptedException ex) {
   Thread.currentThread().interrupt();   // set interrupted status to true
  break;
}

TimerTask task = new TimerTask() {
  public void run() {
   // your concurrent task here
  }

};

Timer timer = new Timer();
timer.schedule(task, 1000, 1000);   // (TimerTask, long delay, long period)


// Better use this instead of java.util.Timer

ExecutorService exec = Executors.newScheduledThreadPool();
// or this
ExecutorService exec = Executors.newSingleThreadScheduledExecutor();

new javax.swing.Timer(1000, new ActionListener() {
      public void actionPerformed( ActionEvent evt) {
          //...Perform a task...
      }
}).start();

Concurrent Collections*
Lists (Collections.synchronizedList) CopyOnWriteArrayList
Sets (Collections.synchronizedSet, Collections.synchronizedSortedSet) CopyOnWriteArraySet, ConcurrentSkipListSet
Maps (Collections.synchronizedMap, Collections.synchronizedSortedMap) ConcurrentMap, ConcurrentHashMap, ConcurrentSkipListMap
Queues

Queue, BlockingQueue, ConcurrentLinkedQueue, ArrayBlockingQueue, LinkedBlockingQueue, PriorityQueue, PriorityBlockingQueue, DelayQueue, SynchronousQueue, Deque, BlockingDeque, ArrayDeque, LinkedBlockingDeque
* Prefer use of the Java 6 concurrent collections instead of the much slower pre Java 5 synchronized ones.

Here's an example of how to use the new API:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadInteractions implements Runnable {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private volatile boolean notified = false;

    public void doWait() {
        System.out.println("Awaiting ...");
        lock.lock();
        while (!notified) {
            try {
                // like wait(), releases the lock
                // and suspends current thread
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        notified = false;
        System.out.println("Resuming ...");
    }

    public void doNotify() {
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("Notifying ...");
            notified = true;
            condition.signal(); // like notify()
            // condition.signalAll(); // like notifyAll()
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        this.doWait();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        ThreadInteractions obj = new ThreadInteractions();
        // a thread executes doWait()
        ExecutorService exec = Executors.newSingleThreadExecutor();
        exec.execute(obj);
        exec.shutdown();
        // the main thread executes doNotify()
        obj.doNotify();
    }
    
}


A thread, created by ExecutorService, calls the doWait() method, while the main method calls doNotify(). Here's the output.

Awaiting ...
Notifying ...
Resuming ...

It is more secure to use condition.signalAll() instead of condition.signal(). For that reason, the notified flag is set back to false in order for the next thread (not in this example however) to set it back to true and the next thread to be notified.

References
  1. Jenkov, J., Introduction to Java Concurrency / Multithreading, http://tutorials.jenkov.com/java-concurrency/index.html
  2. Eckel, B. (2007), Thinking in Java, 4th Edition, Prentice Hall.
  3. Kabutz, H. (1999-2011), Newsletters

Παρασκευή 2 Σεπτεμβρίου 2011

Java Open Spaces Conference 2011 in Chania/Crete

Unfortunately, it's over. A conference different than others, an un-conference! The Java Open Spaces Conference, or Java Specialists Symposium took place from 29th of August till 1st of September 2011 in Perle Resort Spa Hotel at Chania/Greece. A conference different than others. The theme for our 2011 Java Specialists Symposium was: Making Java Fun Again. 


An Open Spaces Conference

The conference was based on the principle of Open Spaces (thanks to Kim and Kate Tucker). In short, this means that we didn't invite key speakers, but the participants organised themselves to suggest topics of interest. This was the reason that no schedule was published even till the last day before the event. However, as you can see here, the magic of open spaces conferences worked and the participants organised themselves to present very interesting and advanced topics. Heinz Kabutz, Kirk Pepperdine, Ben Evans, Michael Hunger, Dimitris Andreadis, Sven Reimers, just to mention a few, led some very interesting discussions on various topics. The outcome of the un-conference will be published under the Creative Commons license.

Excursions

A number of excursions in the afternoon followed the morning sessions. This added substantially to the coherence of the group. The participants enjoyed them and became more attached to each other. We went to some secret beaches, we swam, we tried traditional Cretan delicacies, and for those who preferred something else than sight-seeing there have been programming sessions (puzzlers!) in the evenings. Heinz Kabutz offered his house for a BBQ on Wednesday evening which contributed to a great atmosphere!

The participants loved the whole event. It was a combination of everything: conference, fun, sun, sea, great food, great company. What else can one ask? Ideal for you and your family. See you again next year!

Κυριακή 13 Φεβρουαρίου 2011

FOSDEM 2011

Another FOSDEM (Free Open Source Developers European Meeting) conference took place in the same location, the Universite Libre de Bruxelles (ULB) in 5-6 February 2011. A lot of participants, really, most of the rooms were full and you had to queue a lot of time in advance in order to find a chair to sit.
As a result I missed some interesting talks. A lot of stands of companies too, of OSS but also of OSH (Open Source Hardware) this year.
Some interesting talks:

A number of insteresting stands, as already mentioned:
  • Manpremo a remote management system designed to allow you to control dozens of computers with ease and power
  • CACert - provides free certificates issued to you
  • OpenStreetMap
  • OBM is an enterprise-class messaging and collaboration platform for workgroup and enterprises which includes Groupware, messaging server, CRM, LDAP, Windows Domain, smartphone and PDA synchronisation...
  • Yate - Yet Another Telephone Engine
  • Haiku-OS
  • BeagleBoard
 A summary of the HTML 5 presentation follows.

HTML 5 introduces a lot of goodies like: autocomplete box, email text field, color and date picker, range controls , search bar, input validation, placeholders, autofocus etc. Its main advantage is that for the first time it standardises Javascript, that means you don't need to write different javascript code for the different browsers.
It introduces a Canvas to draw images, play videos etc.
canvas.getContext("2d");
img = document.createElement("path/to/img");
img.addEventListener() ...

Since SVG is also a very powerful library for vector graphics, what does Canvas bring more? Well, use Canvas for speed and SVG for interaction.
<video controls><
<source src="..."  type="video/mp4" media="..."></source><
<video>

It provides a lot of methods for interacting with the video, e.g.
load(), canPlayType(type), play(), pause(), stop(), addTrack() // for subtitles 
etc.
Using these methods you can interact with e.g. a Flash video which was a black box up to HTML 4. CSS3 allows you to interact with the video.
While HTML 4 is stateless, HTML 5 is statefull, i.e. it allows you to store session variables to the web storage.
sessionStorage.setItem(key, value);
localStorage.setItem(key, value);
There is also support for webSQL and indexedDBs but also many TODOs:
  • WebWorkers for multi-threaded Javascript
  • WebSockets for realtime multi-user interaction
  • Audio analysis
  • Face detection
  • Image generation
  • Server side rendering
  • Multi-touch interfaces
  • Device input support (e.g. cameras)
Check the speakers' blogs (found on top of this topic) for more information about these amazing features. And as they finished their presentation:
"We can't change history but we can change the future".

Σάββατο 12 Φεβρουαρίου 2011

Java IDEs

Most popular:
Less popular:

Useful tools/links



ACMQueue programming challenge

Like last year, ACM has already published its challenge (ICPC) for this year and there remain only 1 day for the deadline to submit your player. Good luck!

Java is pass by value

for both primitives and types. More information here.

Java Tutorial Examples

Java Design Patterns

Java Design Patterns are annotations in order to declare the DPs in Java. From the author of Java Specialist's Newsletter.

XSS vulnerability in Tomcat Manager

More information here.

Conferences

LibreOffice



How to write unmaintainable code

What an article.

The ultimate Java puzzler

Find it here.

Rich Internet Applications

When we talk about Rich Internet Applications (RIA), our mind goes to Ajax. Here are some useful links with Ajax libraries:
and IDEs:


Open Source Observatory and Repository (OSOR) Technical platform

ΕΕΛ/ΛΑΚ - Εταιρεία Ελεύθερου Λογισμικού /Λογισμικού Ανοικτού Κώδικα

ΕΕΛ/ΛΑΚ - Εταιρεία Ελεύθερου Λογισμικού /Λογισμικού Ανοικτού Κώδικα

ΔΕΛΤΙΟ ΤΥΠΟΥ
Εταιρεία Ελεύθερου Λογισμικού /Λογισμικού Ανοικτού Κώδικα: Δυναμική Προώθηση και Ανάπτυξη του ΕΛ/ΛΑΚ στο χώρο της Εκπαίδευσης, του Δημόσιου Τομέα και των Επιχειρήσεων

Σημαντικοί φορείς και Ανώτατα Εκπαιδευτικά και Τεχνολογικά Ιδρύματα ενώνουν τις δυνάμεις τους και δραστηριοποιούνται για την επέκταση της χρήσης των εφαρμογών του ΕΛ/ΛΑΚ στη χώρα μας: ιδρύουν την «Εταιρεία Ελεύθερου Λογισμικού /Λογισμικού Ανοικτού Κώδικα» (ΕΕΛ/ΛΑΚ). Η ΕΕΛ/ΛΑΚ, εταιρεία με μη κερδοσκοπικό χαρακτήρα, έχει ως κύριο στόχο να συμβάλλει στην προώθηση και ανάπτυξη του ΕΛ/ΛΑΚ στο χώρο της εκπαίδευσης, του δημόσιου τομέα και των Επιχειρήσεων στην Ελλάδα.

Η εταιρία ΕΕΛ/ΛΑΚ ανταποκρινόμενη στο αυξανόμενο ενδιαφέρον για τα οφέλη της χρήσης του Ελεύθερου Λογισμικού, θα αποτελέσει κέντρο γνώσης και πλατφόρμα διαλόγου για το Ελεύθερο Λογισμικό/Λογισμικό Ανοικτού Κώδικα, και θα αναλάβει πρωτοβουλίες που θα διευκολύνουν και θα επιταχύνουν την διείσδυση του στους παραπάνω τομείς:
• θα ευαισθητοποιήσει το κοινό σχετικά με τα οφέλη που προκύπτουν από την υιοθέτηση και ανάπτυξη του ΕΛ/ΛΑΚ.
• θα φροντίσει για την έγκυρη και έγκαιρη πληροφόρηση σε θέματα που αφορούν το ΕΛ/ΛΑΚ στην Ελλάδα και το διεθνή χώρο (πχ. κωδικοποίηση βέλτιστων πρακτικών, συγκέντρωση και επεξεργασία στοιχείων για την εξέλιξη ποσοτικών και στατιστικών δεικτών, του θεσμικού και νομικού πλαισίου, του διαθέσιμου λογισμικού και εφαρμογών)
• θα εργαστεί ώστε να υπάρξει συνεργασία για την ισότιμη συμμετοχή όλων των άλλων φορέων που έχουν άμεσο ή έμμεσο ρόλο στη διάδοση και ανάπτυξη του ΕΛ/ΛΑΚ στην Ελλάδα, όπως μεταξύ άλλων της κοινότητας προγραμματιστών ΕΛ/ΛΑΚ στην Ελλάδα καθώς και όσων ενδιαφέρονται να αναπτύξουν επιχειρηματική δραστηριότητα που σχετίζεται με το ΕΛ/ΛΑΚ
• θα δημιουργήσει κέντρο παρακολούθησης (monitoring) για το ΕΛ/ΛΑΚ στην Ελλάδα (καταγραφή δράσεων και έργων, καταγραφή διαθέσιμου λογισμικού και εφαρμογών, καταγραφή αναγκών για την εισαγωγή και χρήση του σε διαφορετικούς τομείς, αναγνώριση προβλημάτων στην εισαγωγή/χρήση,
στατιστικά στοιχεία και δείκτες, εξέλιξη θεσμικού και κανονιστικού πλαισίου, βιβλιογραφία, φορείς και οργανώσεις που αφορούν το ΕΛ/ΛΑΚ στην Ελλάδα)
• θα συμβάλει στο συντονισμό των ομάδων εθελοντών προγραμματιστών ΕΛ/ΛΑΚ στην Ελλάδα, ώστε να αποτελέσουν τον βασικό κορμό για την ανάπτυξη και υλοποίηση λογισμικού και εφαρμογών
• θα υποστηρίξει την ανάπτυξη και προώθηση επιχειρηματικών μοντέλων που βασίζονται στο ΕΛ/ΛΑΚ, καθώς και την ενημέρωση των επιχειρήσεων για τηνυιοθέτηση τους ή για τη μετάβαση τους σε αυτά
• θα προσφέρει τεχνική υποστήριξη εφαρμογών ΕΛ/ΛΑΚ και συγκεκριμένα:
δημιουργία υπηρεσίας υποστήριξης (help-desk) για χρήστες και ομάδες ΕΛ/ΛΑΚ, μέριμνα για εξελληνισμό (εντοπιοποίηση) λογισμικού, ανάπτυξη γλωσσάριου, επικουρική ανάπτυξη εφαρμογών για τις οποίες υπάρχει ζήτηση
στην Ελλάδα.Η υλοποίηση όλων των παραπάνω στόχων βασίζεται στην ενεργή συνεργασία
• της ελληνικής κοινότητας χρηστών και δημιουργών εφαρμογών (developers) ΕΛ/ΛΑΚ,
• των εργαστηρίων ΑΕΙ, ΑΤΕΙ και Ερευνητικών Κέντρων της Χώρας που χρησιμοποιούν και αναπτύσσουν ελεύθερο λογισμικό,
• των ενδιαφερόμενων φορέων-χρηστών (δημόσιοι φορείς, εκπαιδευτικοί φορείς και επιχειρήσεις),
• των εταιρειών που δραστηριοποιούνται στους τομείς των τεχνολογιών πληροφορικής και επικοινωνιών που θα οδηγήσουν στη δημιουργία ικανής βάσης επιχειρησιακών μοντέλων υπηρεσιών ανάπτυξης και υποστήριξης ΕΛ/ΛΑΚ.
Φορείς που συμμετέχουν:
Το Εθνικό Δίκτυο Έρευνας και Τεχνολογίας (ΕΔΕΤ Α.Ε), το Εθνικό και Καποδιστριακό Πανεπιστήμιο Αθηνών(ΕΚΠΑ), το Ερευνητικό Κέντρο «Αθηνά», το Εθνικό Κέντρο Τεκμηρίωσης (Ε.Κ.Τ.), το Εθνικό Μετσόβιο Πολυτεχνείο (Ε.Μ.Π.), το Ερευνητικό Πανεπιστημιακό Ινστιτούτο Συστημάτων Επικοινωνιών και
Υπολογιστών (Ε.Π.Ι.Σ.Ε.Υ.), το Ακαδημαϊκό Δίκτυο «GUNET», το Οικονομικό Πανεπιστήμιο Αθηνών (Ο.Π.Α.), η Ελληνική Εταιρεία Επιστημόνων & Επαγγελματιών Πληροφορικής & Επικοινωνιών (Ε.Π.Υ.), το ΕΚΕΦΕ «Δημόκριτος», το Τεχνολογικό Εκπαιδευτικό Ίδρυμα Αθήνας (Α.Τ.Ε.Ι. ΑΘΗΝΑΣ), τo Πανεπιστήμιο
Αιγαίου, το Πανεπιστήμιο Μακεδονίας (Π.Μ.), το Αριστοτέλειο Πανεπιστήμιο Θεσσαλονίκης (Α.Π.Θ.), το Ανώτατο Τεχνολογικό Εκπαιδευτικό Ίδρυμα Καβάλας (Α.Τ.Ε.Ι. ΚΑΒΑΛΑΣ), το Τεχνολογικό Εκπαιδευτικό Ίδρυμα Λάρισας (Α.Τ.Ε.Ι. ΛΑΡΙΣΑΣ), το Πανεπιστήμιο Πατρών (Π.Π.), το Ερευνητικό Ακαδημαϊκό Ινστιτούτο Τεχνολογίας Υπολογιστών (Ε.Α.I.T.Y.), το Πανεπιστήμιο Πελοποννήσου, το Ανώτατο Τεχνολογικό Εκπαιδευτικό Ίδρυμα Καλαμάτας (Α.Τ.Ε.Ι. ΚΑΛΑΜΑΤΑΣ), το Πανεπιστήμιο Κρήτης (Π.Κ) και το Πολυτεχνείο Κρήτης.

Το Διοικητικό Συμβούλιο της ΕΕΛ/ΛΑΚ
κ. Θεόδωρος Καρούνος, Εκπρόσωπος ΕΜΠ, Πρόεδρος
κ. Νεκτάριος Κοζύρης, Εκπρόσωπος ΕΔΕΤ ΑΕ, Αντιπρόεδρος
κ. Αλέξιος Ζάβρας, Στέλεχος της κοινότητας ΕΛ/ΛΑΚ
κ. Κωνσταντίνος Μαργαρίτης, Εκπρόσωπος Πανεπιστημίου Μακεδονίας
κ. Χρήστος Μπούρας, Εκπρόσωπος Πανεπιστημίου Πατρών
κ. Διομήδης Σπινέλλης, Εκπρόσωπος Οικονομικού Πανεπιστημίου Αθηνών
κ. Αύγουστος Τσινάκος, Εκπρόσωπος ΑΤΕΙ Καβάλας
Επικοινωνία: info@ellak.gr, www.ellak.gr ,
Τηλέφωνο: 210-7474-279