Java serialization vs MsgPack vs Bson - java

I am working with websockets, i want the process of sending/recieving data be as fast as possible. I have come across BSON and MsgPack libraries for binary serialization. However, using simple tests:
#Message
class MessageTemplate implements Serializable {
public String msg;
}
public class test {
static void start(){
MessageTemplate x = new MessageTemplate();
for (int i = 0; i < 1000; ++i)
x.msg += UUID.randomUUID().toString();
System.out.println("===============================================================");
{
long startTime = System.nanoTime();
byte[] bytes = SerializationUtils.serialize(x);
MessageTemplate x1 = (MessageTemplate) SerializationUtils.deserialize(bytes);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + bytes.length);
}
System.out.println("===============================================================");
MessagePack msgpack = new MessagePack();
{
long startTime = System.nanoTime();
try {
byte[] b = msgpack.write(x);
MessageTemplate dst = msgpack.read(b, MessageTemplate.class);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + b.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
starting===============================================================
TIME1:2560388, SIZE: 36171
===============================================================
TIME1:93729732, SIZE: 36013
It seems that serialization is way faster than MsgPack. However searching i have found not any mentioning of java serialization as "serializating library/format".
What are the drawbacks of using it? Why is it or isnt used? The only drawback i see is that mobile app will have ios/android client, so there wont be java on both sides in every case.
Thanks for help and answers.

Related

java multithreading in android

how to solve the problem in the log cat .. the error says wait time is negative and it crashes on imulator and external device
this is my code in java android activity
public void run() {
long startTime;
long timeMills;
long waitTime;
long totalTime = 0;
int frameCount = 0;
long targetTime = 1000/FPS;
while (running){
startTime = System.nanoTime();
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder){
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(canvas != null){
try {
surfaceHolder.unlockCanvasAndPost(canvas);
}catch (Exception e){
e.printStackTrace();
}
}
}
timeMills = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMills;
try {
this.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
totalTime += System.nanoTime() - startTime;
frameCount++;
if(frameCount == FPS){
avrageFPS = 1000 / (totalTime/frameCount) / 1000;
frameCount = 0;
totalTime = 0;
System.out.print(avrageFPS);
}
}
}
and this is the log
java.lang.IllegalArgumentException: millis < 0: -136
Your code does this:
long targetTime = 1000/FPS;
while (...) {
startTime = System.nanoTime();
... do lots of work ...
timeMills = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMills;
If the time required to prepare and render a frame exceeds targetTime, then waitTime will be negative. The complexity of your animation, and the value for FPS, affect how likely this is to happen.
The easiest fix is simply:
if (waitTime < 0) { waitTime = 0; }
That way, if your rendering is taking too long and you're missing deadlines, you don't sleep at all.
A better fix would be to structure the game to run off the display's timing, rather than having a fixed notion of frame rate, and to drop frames when you fall behind. More information about this can be found in this appendix to the graphics architecture doc.

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

I created this simple example which is used to read Linux uptime:
public String getMachineUptime() throws IOException {
String[] dic = readData().split(" ");
long s = (long) Array.get(dic, 1);
return calculateTime(s);
}
private String readData() throws IOException {
byte[] fileBytes;
File myFile = new File("/proc/uptime");
if (myFile.exists()) {
try {
fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
return null;
}
if (fileBytes.length > 0) {
return new String(fileBytes);
}
}
return null;
}
private String calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds)
- TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds)
- TimeUnit.DAYS.toMinutes(day)
- TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds)
- TimeUnit.DAYS.toSeconds(day)
- TimeUnit.HOURS.toSeconds(hours)
- TimeUnit.MINUTES.toSeconds(minute);
return "Day " + day + " Hour " + hours + " Minute " + minute
+ " Seconds " + second;
}
When I run the code I get this exception:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
Is there any other way to convert the result?
I believe you have to replace
long s = (long) Array.get(dic, 1);
with
long s = Long.valueOf((String) Array.get(dic, 1));
or even better:
long s = Long.valueOf(dic[1]);
The reason is that your array consists of String object, and direct casting won't work.
The problem appears to be in the following line:
long s = (long) Array.get(dic, 1);
The get(Object array, int index) method of java.lang.reflect.Array returns an instance of Object, which cannot be directly cast to long.
You can access the element of the array simply by dic[1] instead of Array.get(dic, 1)
Replace with the following code:
long s = Long.parseLong(dic[1]);

Extract icons from files takes too long

I need to display lots of files with filename and icon in my program.
Therefor I am extracting the icons from the files, but it takes too long.
I have tried 2 different methods to extract the icons, but both are really slow (in my case REALLY slow, because I get the files from a networkdrive).
Here is an example, where I extract the icons and count the number of icons (do nothing with the files/icons)
public class Main {
public static void main(String[] args) {
File folder = new File("C:\\Windows\\System32\\");
File[] list = folder.listFiles();
for(int i = 0; i< 3; i++) {
long startTime = System.currentTimeMillis();
System.out.println("Method 1: " + getIconNumber1(list)+ " Icons");
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Finished Method 1 in " + (float) elapsedTime / 1000 + "sec");
long startTime2 = System.currentTimeMillis();
System.out.println("Method 2: " + getIconNumber2(list)+ " Icons");
long stopTime2 = System.currentTimeMillis();
long elapsedTime2 = stopTime2 - startTime2;
System.out.println("Finished Method 2 in " + (float) elapsedTime2 / 1000 + "sec");
System.out.println("-----------------");
}
}
private static int getIconNumber1(File[] list) {
int nr = 0;
for(File f : list) {
try {
ShellFolder sf = ShellFolder.getShellFolder(f);
ImageIcon icon = new ImageIcon(sf.getIcon(true));
nr++;
} catch (Exception e) {
e.printStackTrace();
}
}
return nr;
}
private static int getIconNumber2(File[] list) {
int nr = 0;
for(File f : list){
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(f);
nr++;
}
return nr;
}
}
Is there a faster way to do this?

(Java using eclipse) currentTimeMillis()

This is just a piece of what I am working at the moment I want to use currentTimeMillis() to print the time for an image to be loaded any reasons why it does not work?
package method;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
public class TracingInvocationHandler implements InvocationHandler {
private Object target;
private PrintWriter out;
public TracingInvocationHandler(Object target, PrintWriter out) {
this.target = target;
this.out = out;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long startTime = System.currentTimeMillis();
Object result = null;
out.println("Image " + method.getName() + " (...) entered.");
result = method.invoke(target, args);
out.println("Image " + method.getName() + " (...) returned.");
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date().toString(), method.getName(),args[0], (endTime - startTime) + "ms");
return result;
}
public static Object createProxy(Object target, PrintWriter out) {
Class<?> targetClass = target.getClass();
ClassLoader currentClassLoader = targetClass.getClassLoader();
Class<?>[] interfaces = targetClass.getInterfaces();
InvocationHandler handler = new TracingInvocationHandler(target, out);
return Proxy.newProxyInstance(currentClassLoader, interfaces, handler);
}
Remove + "ms" from (endTime - startTime) + "ms". The corresponding format %d in the pattern expects a numeric object. (endTime - startTime) + "ms" produces a String.
You probably were receiving an exception. Next time you ask a question, please include it. This time you were lucky.
It's because you are casting a long primitive to float, I recommend you to use a variable where you cast: for example:
long totalTime = endTime - startTime;
String strTotalTime = String.valueOf(totalTime);
System.out.printf(" [%s] %s Image %s took %s ms:",
new Date().toString(), method.getName(), args[0], strTotalTime);
Its invoked but I don't see you pass it to sysout, thats why its not visible.
That is you're doing:
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date().toString(),
instead of:
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date(endTime).toString(),

Confusion with Java System.Time

Thank you in advance for your help. I am developing a java based tool that is preforming some database work. I have a very simple problem. For some reason the time reported to complete the task is incorrect.
public static void makeDatabaseThreaded() throws IOException, InterruptedException {
final long startTime = System.nanoTime();
ArrayList<String> tablesMade = new ArrayList<>();
File rootDirectory = root;
String[] files = rootDirectory.list();
double percentDone = 0;
double numOfTablesMade = 0;
double numberOfTables = 62.0;
DatabaseBuilderThread lastThread = null;
for (int i = 0; i <= files.length - 1; i++) {
if (!files[i].contains(".csv")) {
continue;
}
File file = new File(rootDirectory + File.separator + files[i]);
String tableName = getTableNameFromFile(file);
if (!tablesMade.contains(tableName)) {
tablesMade.add(tableName);
DatabaseBuilderThread thread = new DatabaseBuilderThread(i, file);
lastThread = thread;
thread.start();
threadsRunning++;
numOfTablesMade++;
percentDone = (int) (100.0 * (numOfTablesMade) / (numberOfTables));
while (threadsRunning > 10) {
Thread.sleep(1000);
}
System.out.println(percentDone + "% done. Making Table For File: " + file.getName());
}
}
//Make Sure all threads are done
lastThread.join();
final long endTime = System.nanoTime();
final long duration = endTime - startTime;
Time time = new Time(duration);
System.out.println("Done Making The Database. It took " + time.toString());
}
The program reports that it worked about twice as long at it truly did for the cases that I ran.
Thanks
System.nanoTime() returns time values in nanoseconds. Time() takes a value in milliseconds as a parameter. This would throw your time value off by a factor of 10^-6.
Time takes milliseconds as a constructor parameter, where as nanoTime() gives you nanoseconds precision, could that be the problem?
discussion here: System.currentTimeMillis vs System.nanoTime

Categories

Resources