我正在做一些关于单身人士的研究,特别是关于单身人士的懒惰与急切初始化.
急切初始化的一个例子:
public class Singleton
{
//initialzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
但如上所示,它是急切的初始化和线程安全留给jvm但现在,我希望有相同的模式,但延迟初始化.
所以我想出了这个方法:
public final class Foo {
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
如上图所示 …
在访谈中,我们要求有一个Class A没有实现serializable如下所示的界面
class A
{
private int a;
A( int a)
{
this.a = a;
}
}
Run Code Online (Sandbox Code Playgroud)
并且有一个B扩展A并实现serializable接口的类
class B extends A implements serializable
{
private int a , b;
B(int a, int b)
{
this.a = a;
this.b = b;
}
}
Run Code Online (Sandbox Code Playgroud)
现在请告诉我是否可以序列化类B,只要该类A没有序列化,假设我想序列化类的对象B,可以这样做.
我是java世界的新bie并探索并发哈希映射,在探索并发hashmap API时,我发现了putifAbsent()方法
public V putIfAbsent(K paramK, V paramV)
{
if (paramV == null)
throw new NullPointerException();
int i = hash(paramK.hashCode());
return segmentFor(i).put(paramK, i, paramV, true);
}
Run Code Online (Sandbox Code Playgroud)
现在请告知它的功能是什么,我们什么时候需要它,如果可能的话请用一个简单的小例子来解释.