zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Guava的Supplier实现单例详解编程语言

编程语言 实现 详解 单例 Guava SUPPLIER
2023-06-13 09:20:46 时间
//shouldInitTheSupplierWrappedObjectWhenGetObject(); shouldInitTheSupplierWrappedObjectForOnlyOneTime(); } catch (Exception e) { e.printStackTrace(); private static void shouldInitTheSupplierWrappedObjectWhenGetObject() throws Exception { Supplier Integer memoize = Suppliers.memoize(new Supplier Integer () { @Override public Integer get() { System.out.println("init supplier wrapped object"); return 1; }); System.out.println("main thread block"); Thread.sleep(2000); System.out.println(memoize.get()); System.out.println(memoize.get()); private static void shouldInitTheSupplierWrappedObjectForOnlyOneTime() { Supplier Admin memoize = Suppliers.memoize(new Supplier Admin () { @Override public Admin get() { System.out.println("init supplier wrapped object"); ServiceLoader Admin loader = ServiceLoader.load(Admin.class); return Iterables.getFirst(loader, null); }); System.out.println(memoize.get()); System.out.println(memoize.get()); System.out.println(memoize.get()); }

 

package suppliers; 

 * @author xfyou 

 * @date 2018/7/31 

public interface User { 

 /** 

 * @param firstName 

 * @param lastName 

 void addUser(String firstName, String lastName); 

}

 

package suppliers; 

import lombok.ToString; 

import java.util.concurrent.atomic.AtomicReference; 

 * @author xfyou 

 * @date 2018/7/31 

@ToString 

public class Admin implements User { 

 private static final AtomicReference Admin INSTANCE = new AtomicReference (); 

 public Admin() { 

 if (!INSTANCE.compareAndSet(null, this)) { 

 throw new IllegalStateException("This class only can be initialized once"); 

 } else { 

 System.out.println("Construct"); 

 @Override 

 public void addUser(String firstName, String lastName) { 

 System.out.println("Add new user"); 

}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15922.html

cgojava