java单例中使用weakreference的对象是否可以被回收
retrofit是够需要使用单例 将retrofit放入weakreference中
public class RetrofitSingleton {
private WeakReference<Retrofit> retrofitWeakReference;
private RetrofitSingleton() {
}
private static volatile RetrofitSingleton instance = null;
public static RetrofitSingleton getInstance() {
if (instance == null) {
synchronized (RetrofitSingleton.class) {
if (instance == null) {
instance = new RetrofitSingleton();
}
}
}
return instance;
}
private synchronized Retrofit getRetrofit() {
if (retrofitWeakReference == null) {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new TokenHeadweInterceptor())
.readTimeout(8, TimeUnit.SECONDS)
.writeTimeout(8, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(GsonUtil.buildGosn()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
retrofitWeakReference = new WeakReference<>(retrofit);
}
return retrofitWeakReference.get();
}
}
会回收,和是否单例无关,只要对象没被其它人引用就会回收。