Friday, 4 October 2013

Daemon Threads

A “daemon” thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated. Conversely, if there are any non-daemon threads still running, the program doesn’t terminate. There is, for instance, a non-daemon thread that runs main( ).
//: c13:SimpleDaemons.java
// Daemon threads don't prevent the program from ending.

public class SimpleDaemons extends Thread {
  public SimpleDaemons() {
    setDaemon(true); // Must be called before start()
    start();
  }
  public void run() {
    while(true) {
      try {
        sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      System.out.println(this);
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new SimpleDaemons();
  }
} ///:~

You must set the thread to be a daemon by calling setDaemon( ) before it is started. In run( ), the thread is put to sleep for a little bit. Once the threads are all started, the program terminates immediately, before any threads can print themselves, because there are no non-daemon threads (other than main( )) holding the program open. Thus, the program terminates without printing any output.
You can find out if a thread is a daemon by calling isDaemon( ). If a thread is a daemon, then any threads it creates will automatically be daemons, as the following example demonstrates:
//: c13:Daemons.java
// Daemon threads spawn other daemon threads.
import java.io.*;
import com.bruceeckel.simpletest.*;

class Daemon extends Thread {
  private Thread[] t = new Thread[10];
  public Daemon() {
    setDaemon(true);
    start();
  }
  public void run() {
    for(int i = 0; i < t.length; i++)
      t[i] = new DaemonSpawn(i);
    for(int i = 0; i < t.length; i++)
      System.out.println("t[" + i + "].isDaemon() = "
        + t[i].isDaemon());
    while(true)
      yield();
  }
}

class DaemonSpawn extends Thread {
  public DaemonSpawn(int i) {
    start();
    System.out.println("DaemonSpawn " + i + " started");
  }
  public void run() {
    while(true)
      yield();
  }
}

public class Daemons {
  private static Test monitor = new Test();
  public static void main(String[] args) throws Exception {
    Thread d = new Daemon();
    System.out.println("d.isDaemon() = " + d.isDaemon());
    // Allow the daemon threads to
    // finish their startup processes:
    Thread.sleep(1000);
    monitor.expect(new String[] {
      "d.isDaemon() = true",
      "DaemonSpawn 0 started",
      "DaemonSpawn 1 started",
      "DaemonSpawn 2 started",
      "DaemonSpawn 3 started",
      "DaemonSpawn 4 started",
      "DaemonSpawn 5 started",
      "DaemonSpawn 6 started",
      "DaemonSpawn 7 started",
      "DaemonSpawn 8 started",
      "DaemonSpawn 9 started",
      "t[0].isDaemon() = true",
      "t[1].isDaemon() = true",
      "t[2].isDaemon() = true",
      "t[3].isDaemon() = true",
      "t[4].isDaemon() = true",
      "t[5].isDaemon() = true",
      "t[6].isDaemon() = true",
      "t[7].isDaemon() = true",
      "t[8].isDaemon() = true",
      "t[9].isDaemon() = true"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

The Daemon thread sets its daemon flag to “true” and then spawns a bunch of other threads—which do not set themselves to daemon mode—to show that they are daemons anyway. Then it goes into an infinite loop that calls yield( ) to give up control to the other processes.
There’s nothing to keep the program from terminating once main( ) finishes its job, since there are nothing but daemon threads running. So that you can see the results of starting all the daemon threads, the main( ) thread is put to sleep for a second. Without this, you see only some of the results from the creation of the daemon threads. (Try sleep( ) calls of various lengths to see this behavior.)

Thursday, 3 October 2013

Bubble Sort

Bubble Sort
Pseudocode and Flowchart

BubbleSort( int a[], int n)

Begin
 for i = 1 to n-1
  sorted = true
       for j = 0 to n-1-i
                 if a[j] > a[j+1]
                 temp = a[j]
                 a[j] = a[j+1]
                 a[j+1] = temp
           sorted = false
        end for
       if sorted
         break from i loop
 end for
End


Bubble sort uses a loop (inside j loop) to travel thru’ an array comparing adjacent
values as it moves along. If an array element a[j] is greater than the element
immediately to its right a[j+1], it swaps them. The first time around, this process will
move or bubble the largest value to the end of the array. So for instance

5 3 1 9 8 2 4 7
will end up as
3 1 5 8 2 4 7 9


This process is repeated, on the second iteration, the second largest value will be
moved to the second last array position and so on.

In all, the bubble process (inside j loop) is repeated n-1 times for an array of size n.

Note for array of size 8, outside i loop repeats 7 times.
Complexity
Clearly for an array of size n, the outside loop repeats n-1 times.

To begin with the inside loop does n-1 comparisons, next time n-2 and so on. Finally
on the last iteration of the outside loop, the inside loop does 1 comparison. So on
average the inside loop does ((n-1) + 1) / 2 ≈ n/2 comparisons.

Therefore, the overall number of computation steps is n * n/2 = n2/2

Complexity of bubble sort = O(n2)

Wednesday, 2 October 2013

Examples from Java I/O, 2nd Edition

The complete set of examples is also available for anonymous from ftp://ftp.ibiblio.org/pub/languages/java/javafaq/ioexamples2.zip 

Please feel free to use any fragment of this code you need in your own work. As far as I am concerned, it's in the public domain. No permission is necessary or required. Credit is always appreciated if you use a large chunk or base a significant product on one of my examples, but that's not required either.

How would I do $push using MongoRepository in Spring Data?

Yes, you must implement a custom method on the repository and your push method would be something like this :


public class FooRepositoryImpl implements
    AppointmentWarehouseRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushMethod(String objectId, Object... events) {
        mongoTemplate.updateFirst(
            Query.query(Criteria.where("id").is(objectId)), 
            new Update().pushAll("events", events), Foo.class);
    }
}
You can do this but I ran into an issue where the "_class" field wasn't being preserved. 
The pushed object itself was run through the configured converter but for some reason the "_class" field of that pushed object wasn't written. 
However, if I injected the converter and wrote the object to a DBObject myself, then the "_class" field was preserved and written. The thus becomes:

public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {

@Autowired
protected MongoTemplate mongoTemplate;

public void pushMethod(String objectId, Object event) {
    DBObject eventObj = new BasicDBObject();
    converter.write(event, eventObj);
    mongoTemplate.updateFirst(
        Query.query(Criteria.where("id").is(objectId)), 
        new Update().push("events", eventObj), Foo.class);
  }
}

Flip in image in JavaFX


For Flip Horizontal

You can do this by setting the scaleX variable of the ImageView to -1.

For Flip Vertical

You can do this by setting the scaleY variable of the ImageView to -1.

Tuesday, 1 October 2013

ImageJ: Create ImageStack for dicom 2d slice

Hello friends following code for make ImagePlus by given path and also modify your code in your own way...enjoy..!!!!
package imagejexample;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.io.Opener;
import ij.process.ImageProcessor;
import java.awt.image.ColorModel;
import java.io.File;
/**
*
* @author Jay.Thakkar
*/
public class TestInput {
public static void main(String[] args) {
TestInput testInput = new TestInput();
testInput.run();
}
private static boolean grayscale;
private static boolean halfSize;
public void run() {
String dir = "D:\\testImaes\\skull\\";
String[] list = new File(dir).list();
System.out.println("### Size()::" + list.length);
int n = list.length;
int width = 0, height = 0, type = 0;
ImageStack stack = null;
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
int k = 0;
try {
for (int i = 0; i < n; i++) {
String path = (dir + list[i]);
if (path == null) {
break;
}
if (list[i].endsWith(".txt")) {
continue;
}
//System.out.println("Path:"+path);
ImagePlus imp = new Opener().openImage(path);
if (imp != null && stack == null) {
width = imp.getWidth();
height = imp.getHeight();
type = imp.getType();
ColorModel cm = imp.getProcessor().getColorModel();
if (halfSize) {
stack = new ImageStack(width / 2, height / 2, cm);
} else {
stack = new ImageStack(width, height, cm);
}
}
if (stack != null) {
k = stack.getSize() + 1;
}
if (imp == null) {
IJ.log(list[i] + ": unable to open");
} else if (imp.getWidth() != width || imp.getHeight() != height) {
IJ.log(list[i] + ": wrong dimensions");
} else if (imp.getType() != type) {
IJ.log(list[i] + ": wrong type");
} else {
ImageProcessor ip = imp.getProcessor();
if (grayscale) {
ip = ip.convertToByte(true);
}
if (halfSize) {
ip = ip.resize(width / 2, height / 2);
}
if (ip.getMin() < min) {
min = ip.getMin();
}
if (ip.getMax() > max) {
max = ip.getMax();
}
String label = imp.getTitle();
String info = (String) imp.getProperty("Info");
if (info != null) {
label += "\n" + info;
}
stack.addSlice(label, ip);
}
System.gc();
}
} catch (OutOfMemoryError e) {
IJ.outOfMemory("FolderOpener");
stack.trim();
}
if (stack != null && stack.getSize() > 0) {
ImagePlus imp2 = new ImagePlus("Stack", stack);
if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) {
imp2.getProcessor().setMinAndMax(min, max);
}
imp2.show();
}
}
}
view raw CustomImagePlus hosted with ❤ by GitHub

Monday, 30 September 2013

Can we synchronize static method/variable in a Java class?


Yes, you can do it.
A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. The following example show you few ways to access the class object:
class MyClass {


    public static void main(String[] args) {
        //you can access class object through an instance of that class
        MyClass objectinstance = new MyClass();
        java.lang.Class myclass1 = objectinstance.getClass();

        //non-instance ways
        java.lang.Class myclass2 = Myclass.class;
 java.lang.Class myclass3 = Class.forName("MyClass");
    }

}
The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.
For example
class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  ...
}
It is the equivalent to the following static synchronized block:
synchronized ( MyClass.class ) {
...
}
In some situatios, you need to protect access static variables, the locking an object instance does not automatically protect access to static variables, because there may have more than one instances and all of them use the same static variables. You have to obtain a lock on the Class vs an instance of the class. A static synchronized block can be use to protect access to static varibales, a lock on a static method has no effect on any instances of that class (see the Java Language Specification). For example,
class BumpTest {

 int count;
 static int classCount;
 void synchronized bump() {
  count++;

  try {
   synchronized (BumpTest.class) { 
                        //or synchronized (Class.forname("BumpTest"))
    classCount++;
   }
  } catch (ClassNotFoundException e) {
 }
    ...
}
Static variables, like static methods, are not inherited, but are accessible from within the body of the class definition and through an explicit reference to the defining class's name. Adding a new static synchronized method in a subclass cannot protect other threads to access static variables defined in its superclass nor should you use synchronized(this.getClass()) which locks the actual Class might be the subclass. An explicit block synchronization with "none-instance way to get Class" is the preferred way.

 synchronized Methods
A synchronized method acquires a monitor  before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.