Tuesday, July 24, 2018

Java Misc Part 6



https://gwoham-163-com.iteye.com/blog/2086929
java中,按位或操作符是"^"



java中,按位或操作符是"|"
Java 中,取反操作符用波浪线"~"表示。值得注意的是此操作符与"逻辑非(!)" 操作符不同,"逻辑非"并不是一个位操作。

按位取反
移位是一个二元运算符,用来将一个二进制数中的每一位全部都向一个方向移动指定位,溢出的部分将被舍弃,而空缺的部分填入一定的值。在Java中,左移使用两个小于符号"<<"表示,右移使用两个大于符号">>"表示。">>" 右移,高位补符号位” 这里右移一位表示除2 ">>>" 无符号右移,高位补0”; 与>>类似。
应用逻辑移位时,移位后空缺的部分全部填0.
0001 (十进制 1) << 3 (左移 3 位) = 1000 (十进制 8) 1010 (十进制 10) >> 2 (右移 2 位) = 0010 (十进制 2)
https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
"user.dir"User working directory
"user.home"User home directory

https://stackoverflow.com/questions/9545076/access-variables-of-outer-class-in-java

If the dialog variable is a field of the outer class, you can use this prefixed with the outer class name (a qualified this):
send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       ProgressDialog dlg = OuterClass.this.dialog;
       .......
    }
});
Alternatively, if the dialiog variable is a local variable it needs to be marked as final:
final ProgressDialog dialog = new ProgressDialog(this);
.....
send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       // The dialog variable is in scope here ...
       dialog.someMethod();
    }
});
Make the outer local variable (dialogfinal so you can refer to it from the inner class.
If it's a local variable (like the signature suggests), it needs to be final for the inner class to be able to access it. If it's a member variable, the visibility modifier needs to be default (no modifier) or higher (protected or public). With private -modifier, it still works, but you might get a warning (depending on your compiler-settings):
Read access to enclosing field SomeClass.someField is emulated by a synthetic accessor method
https://stackoverflow.com/questions/1677037/how-can-i-reference-my-java-enum-without-specifying-its-type

import static mypackage.Test.MyEnum.*;
https://stackoverflow.com/questions/17481251/finally-block-does-not-complete-normally-eclipse-warning
remove return statement from it. Final block is considered to be cleanup block, return is not generally expected in it.
The return from finally "overrides" further exception throwing.
Generally a finally block should never have a return statement because it would overwrite other return-statements or Exceptions.

https://mp.weixin.qq.com/s/QGI1wIB4NYZW8Gf-xBpl5Q
final ReentrantLock lock = this.lock
从java内存模型中可以看出,method只会存放对象引用(this指针),不会存放对象中的信息,只能再次通过this访问对象中的信息。
所以这种写法,在访问lock的时候首先去访问this对象,然后获取lock的引用,最后再调用lock函数,每次访问lock中的函数都是这3步。
但是如果采用将字段赋值给局部变量在使用,之后就不需要访问this指针,少了一步操作. 也就是说this对象和其他普通对象在函数没有任何区别

https://dzone.com/articles/if-youre-using-javas-scanner-class-for-keyboard-in
 If  System.in, a BufferedInputStream from the keyboard, is closed, as happens when the Scanner object is closed, you are closing a System stream that cannot be re-opened. The program must be exited and then re-run to re-establish  System.in.
https://www.opsian.com/blog/java-on-docker/
By default, on 64-bit servers, the JVM will set a maximum heap size of up to 1/4th of physical memory. This really isn’t helpful in a containerised environment as you often have a host with significant amounts of memory that could run many JVMs. If you run 10 JVMs in different containers and they each end up using ¼ of the RAM then you overcommit the machines’ RAM and potentially end up hitting swap - causing sad times for your users.

It also nullifies one of the advantages of containerisation, that the container image built and tested will perform the same in production. An image could easily work fine in a staging environment on a smaller physical host but then on a larger host in production could exceed any memory limit for the container and get killed by the kernel.

The primary mechanism for isolating containers on Linux is via Control Groups (cgroups), these allow for (amongst other things) limiting resources to a group of processes. With Java 10 the JVM will now read memory limits and usage from the container’s cgroup and use this to initialise maximum memory, removing the need for any of these workarounds.

As of Java 8u131 and Java 9, the JVM could understand and utilise cpusets for sizing available processors while Java 10 brings support for CPU shares.

All processes in on mainstream Operating Systems have a unique identifier, the PID. Linux also has the concept of PID namespaces where two processes in different namespaces can share the same PID. Namespaces can also be nested and this functionality is used to isolate processes inside a container.

The complication for the attach mechanism is that the JVM inside of the container currently has no concept of its PID outside the container. Java 10 fixes this by the JVM inside the container finding its PID in the root namespace and using this to watch for a JVM attachment.

https://medium.com/codefx-weekly/no-free-java-lts-version-b850192745fb
Not only is it moving Java to a six-months release train, it is now likely that users will have to make each jump immediately if they want to keep getting free updates. That’s right, Oracle will no longer be providing free long-term support.
Every major release $X will see two public updates $X.0.1 one month after release (e.g. Java 10.0.1 in April) and $X.0.2 three more months down the road (e.g. Java 10.0.2 in July). Then it's just two more months to the next feature release.
[The] intent is that within a few releases there should be no technical differences between OpenJDK builds and Oracle JDK binaries.
Java 8 introduced the removeIf() method to the Collection interface. This means that if we are working with it, we can use ideas of functional programming to achieve the same results again:
1
2
3
4
5
List<Integer> integers = newArrayList(1, 2, 3);
integers.removeIf(i -> i == 2);
assertThat(integers).containsExactly(1, 3);
2. Triggering a ConcurrentModificationException
    List<Integer> integers = newArrayList(1, 2, 3);
    for (Integer integer : integers) {
        integers.remove(1);
    }


Detect Java Pause
https://github.com/opentable/otj-pausedetector/blob/master/src/main/java/com/opentable/pausedetector/JvmPauseAlarm.java

https://stackoverflow.com/questions/28495280/how-to-detect-a-long-gc-from-within-a-jvm
You can use management bean notifications and subscribe to GARBAGE_COLLECTION_NOTIFICATION events which in turn provide GcInfo objects with the stats you want.
GarbageCollectionNotificationInfo


https://dzone.com/articles/interface-default-methods-java
When we extend an interface that contains a default method, we can perform following,
  • Redeclare default method as abstract, which force subclass to override it.
https://docs.oracle.com/javase/tutorial/essential/io/links.html
    Files.createSymbolicLink(newLink, target);
    Files.createLink(newLink, existingFile);
boolean isSymbolicLink =
    Files.isSymbolicLink(file);
    System.out.format("Target of link" +
        " '%s' is '%s'%n", link,
        Files.readSymbolicLink(link));

https://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html

NoClassDefFoundError in Java due to Exception in Static Initializer block

This is another common reason of java.lang.NoClassDefFoundError, when your class performs some static initialization in a static block like many Singleton classes initialized itself on the static block  to take advantage of thread-safety provided by JVM during the class initialization process, and if static block throws an Exception, the class which is referring to this class will get NoclassDefFoundError in Java. If you look at your log file you should watch for any java.lang.ExceptionInInitializerError because that could trigger java.lang.NoClassDefFoundError: Could not initialize class on other places.

If you look at your log file you should watch for any java.lang.ExceptionInInitializerError because that could trigger java.lang.NoClassDefFoundError: Could not initialize class on other places. Like in below code example, During class loading and initialization User class are throwing Exception from static initializer block, which trigger ExceptionInInitializerError during first time loading of User class in response to new User() call. Later rest of new User() are failing as java.lang.NoClassDefFoundError. the situation gets worst if original ExceptionInInitializerError, which is root cause here is silently eaten by any code.


5) Since NoClassDefFoundError is an  also a LinkageError which arises due to dependency on some other class, you can also get java.lang.NoClassDefFoundError if your program is dependent on native library and the corresponding DLL is not there. Remember this can also trigger java.lang.UnsatisfiedLinkError: no dll in java.library.path Exception JavaIn order to solve this keep your dll along with JAR.


4) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.

https://javarevisited.blogspot.com/2011/07/classnotfoundexception-vs.html

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using ClassLoader in Java and have two class loaders then if a ClassLoader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass()Class.forName(),  while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts