List of usage examples for java.util.concurrent ThreadPoolExecutor ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
From source file:org.wso2.siddhi.extension.output.transport.http.HttpOutputTransport.java
@Override public void init(String type, Map<String, String> options, Map<String, String> unmappedDynamicOptions) { if (executorService == null) { int minThread = (options.get(ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) ? Integer.parseInt(options.get(ADAPTER_MIN_THREAD_POOL_SIZE_NAME)) : ADAPTER_MIN_THREAD_POOL_SIZE; int maxThread = (options.get(ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) ? Integer.parseInt(options.get(ADAPTER_MAX_THREAD_POOL_SIZE_NAME)) : ADAPTER_MAX_THREAD_POOL_SIZE; long defaultKeepAliveTime = (options.get(ADAPTER_KEEP_ALIVE_TIME_NAME) != null) ? Integer.parseInt(options.get(ADAPTER_KEEP_ALIVE_TIME_NAME)) : DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS; int jobQueSize = (options.get(ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) ? Integer.parseInt(options.get(ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME)) : ADAPTER_EXECUTOR_JOB_QUEUE_SIZE; int defaultMaxConnectionsPerHost = (options.get(DEFAULT_MAX_CONNECTIONS_PER_HOST) != null) ? Integer.parseInt(options.get(DEFAULT_MAX_CONNECTIONS_PER_HOST)) : DEFAULT_DEFAULT_MAX_CONNECTIONS_PER_HOST; int maxTotalConnections = (options.get(MAX_TOTAL_CONNECTIONS) != null) ? Integer.parseInt(options.get(MAX_TOTAL_CONNECTIONS)) : DEFAULT_MAX_TOTAL_CONNECTIONS; executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(jobQueSize)); connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnectionsPerHost); connectionManager.getParams().setMaxTotalConnections(maxTotalConnections); }//from www. j a va 2s . c om }
From source file:org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIEventAdapter.java
@Override public void init() throws OutputEventAdapterException { tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); //ExecutorService will be assigned if it is null if (executorService == null) { int minThread; int maxThread; long defaultKeepAliveTime; int jobQueSize; //If global properties are available those will be assigned else constant values will be assigned if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) { minThread = Integer/* ww w . j av a 2 s . c o m*/ .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME)); } else { minThread = UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) { maxThread = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME)); } else { maxThread = UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) { defaultKeepAliveTime = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME)); } else { defaultKeepAliveTime = UIEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS; } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) { jobQueSize = Integer.parseInt( globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME)); } else { jobQueSize = UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE; } executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(jobQueSize)); } streamId = eventAdapterConfiguration.getOutputStreamIdOfWso2eventMessageFormat(); if (streamId == null || streamId.isEmpty()) { throw new OutputEventAdapterRuntimeException("UI event adapter needs a output stream id"); } // fetch the "streamDefinition" corresponding to the "streamId" and then fetch the different attribute types // of the streamDefinition corresponding to the event's streamId. They are required when validating values in // the events against the streamDef attributes. StreamDefinition streamDefinition = getStreamDefinition(streamId); streamMetaAttributes = streamDefinition.getMetaData(); streamCorrelationAttributes = streamDefinition.getCorrelationData(); streamPayloadAttributes = streamDefinition.getPayloadData(); ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>> tenantSpecifcEventOutputAdapterMap = UIEventAdaptorServiceDataHolder .getTenantSpecificOutputEventStreamAdapterMap(); ConcurrentHashMap<String, String> streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId); if (streamSpecifAdapterMap == null) { streamSpecifAdapterMap = new ConcurrentHashMap<>(); if (null != tenantSpecifcEventOutputAdapterMap.putIfAbsent(tenantId, streamSpecifAdapterMap)) { streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId); } } String adapterName = streamSpecifAdapterMap.get(streamId); if (adapterName != null) { throw new OutputEventAdapterException(("An Output ui event adapter \"" + adapterName + "\" is already" + " exist for stream id \"" + streamId + "\"")); } else { streamSpecifAdapterMap.put(streamId, eventAdapterConfiguration.getName()); ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>> tenantSpecificStreamMap = UIEventAdaptorServiceDataHolder .getTenantSpecificStreamEventMap(); ConcurrentHashMap<String, LinkedBlockingDeque<Object>> streamSpecificEventsMap = tenantSpecificStreamMap .get(tenantId); if (streamSpecificEventsMap == null) { streamSpecificEventsMap = new ConcurrentHashMap<>(); if (null != tenantSpecificStreamMap.putIfAbsent(tenantId, streamSpecificEventsMap)) { streamSpecificEventsMap = tenantSpecificStreamMap.get(tenantId); } } streamSpecificEvents = streamSpecificEventsMap.get(streamId); if (streamSpecificEvents == null) { streamSpecificEvents = new LinkedBlockingDeque<>(); if (null != streamSpecificEventsMap.putIfAbsent(streamId, streamSpecificEvents)) { streamSpecificEvents = streamSpecificEventsMap.get(streamId); } } } if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME) != null) { try { queueSize = Integer .parseInt(globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME)); } catch (NumberFormatException e) { log.error("String does not have the appropriate format for conversion." + e.getMessage()); queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; } } else { queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; } }
From source file:com.serotonin.m2m2.Lifecycle.java
public synchronized void initialize(ClassLoader classLoader) { for (Module module : ModuleRegistry.getModules()) { module.preInitialize();// w w w.j av a2 s . c o m } String tzId = Common.envProps.getString("timezone"); if (!StringUtils.isEmpty(tzId)) { TimeZone tz = TimeZone.getTimeZone(tzId); if ((tz == null) || (!tz.getID().equals(tzId))) throw new RuntimeException("Time zone id '" + tzId + "' in env properties is not valid"); this.LOG.info("Setting default time zone to " + tz.getID()); TimeZone.setDefault(tz); DateTimeZone.setDefault(DateTimeZone.forID(tzId)); } Common.timer.init(new ThreadPoolExecutor(0, 1000, 30L, TimeUnit.SECONDS, new SynchronousQueue())); Providers.add(TimerProvider.class, new TimerProvider() { public AbstractTimer getTimer() { return Common.timer; } }); Common.JSON_CONTEXT.addResolver(new EventTypeResolver(), new Class[] { EventType.class }); Common.JSON_CONTEXT.addResolver(new BaseChartRenderer.Resolver(), new Class[] { ChartRenderer.class }); Common.JSON_CONTEXT.addResolver(new BaseTextRenderer.Resolver(), new Class[] { TextRenderer.class }); Common.JSON_CONTEXT.addResolver(new EmailRecipientResolver(), new Class[] { EmailRecipient.class }); Providers.add(InputStreamEPollProvider.class, new InputStreamEPollProviderImpl()); Providers.add(ProcessEPollProvider.class, new ProcessEPollProviderImpl()); // lic(); freemarkerInitialize(); databaseInitialize(classLoader); for (Module module : ModuleRegistry.getModules()) { module.postDatabase(); } utilitiesInitialize(); eventManagerInitialize(); runtimeManagerInitialize(); maintenanceInitialize(); imageSetInitialize(); webServerInitialize(classLoader); for (Module module : ModuleRegistry.getModules()) { module.postInitialize(); } SystemEventType.raiseEvent(new SystemEventType("SYSTEM_STARTUP"), System.currentTimeMillis(), false, new TranslatableMessage("event.system.startup")); for (Runnable task : this.STARTUP_TASKS) Common.timer.execute(task); }
From source file:com.yozio.android.YozioHelper.java
YozioHelper(YozioDataStore dataStore, YozioApiService apiService) { this.dataStore = dataStore; this.apiService = apiService; this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // This executor MUST have pool size of 1 (1 task allowed to run at once). // Otherwise, we might send the same event multiple times. executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
From source file:Proxy.java
public void start() throws Exception { Map.Entry entry;//from www . j a va 2 s .co m Selector selector; ServerSocketChannel sock_channel; MyInetSocketAddress key, value; if (remote != null && local != null) mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port)); if (mapping_file != null) { try { populateMappings(mapping_file); } catch (Exception ex) { log("Failed reading " + mapping_file); throw ex; } } log("\nProxy started at " + new java.util.Date()); if (verbose) { log("\nMappings:\n---------"); for (Iterator it = mappings.entrySet().iterator(); it.hasNext();) { entry = (Map.Entry) it.next(); log(toString((InetSocketAddress) entry.getKey()) + " <--> " + toString((InetSocketAddress) entry.getValue())); } log("\n"); } // 1. Create a Selector selector = Selector.open(); // Create a thread pool (Executor) executor = new ThreadPoolExecutor(MIN_THREAD_POOL_SIZE, MAX_THREAD_POOL_SIZE, 30000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1000)); for (Iterator it = mappings.keySet().iterator(); it.hasNext();) { key = (MyInetSocketAddress) it.next(); value = (MyInetSocketAddress) mappings.get(key); // if either source or destination are SSL, we cannot use JDK 1.4 // NIO selectors, but have to fall back on separate threads per connection if (key.ssl() || value.ssl()) { // if(2 == 2) { SocketAcceptor acceptor = new SocketAcceptor(key, value); executor.execute(acceptor); continue; } // 2. Create a ServerSocketChannel sock_channel = ServerSocketChannel.open(); sock_channel.configureBlocking(false); sock_channel.socket().bind(key); // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on // select(). That way we can associate it with the mappings hashmap to find the corresponding // value sock_channel.register(selector, SelectionKey.OP_ACCEPT, key); } // 4. Start main loop. won't return until CTRL-C'ed loop(selector); }
From source file:org.apache.hadoop.hbase.client.HBaseFsck.java
/** * Constructor//from www . ja v a2s .c o m * * @param conf Configuration object * @throws MasterNotRunningException if the master is not running */ public HBaseFsck(Configuration conf) throws MasterNotRunningException, IOException { this.conf = conf; // fetch information from master HBaseAdmin admin = new HBaseAdmin(conf); status = admin.getMaster().getClusterStatus(); connection = admin.getConnection(); numThreads = conf.getInt("hbasefsck.numthreads", numThreads); executor = new ThreadPoolExecutor(numThreads, numThreads, THREADS_KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); executor.allowCoreThreadTimeOut(true); }
From source file:org.bimserver.tests.TestSimultaniousDownloadWithCaching.java
private void start() { BimServerConfig config = new BimServerConfig(); Path homeDir = Paths.get("home"); try {/*from ww w .j a va 2 s.com*/ if (Files.isDirectory(homeDir)) { PathUtils.removeDirectoryWithContent(homeDir); } } catch (IOException e) { e.printStackTrace(); } config.setClassPath(System.getProperty("java.class.path")); config.setHomeDir(homeDir); config.setPort(8080); config.setStartEmbeddedWebServer(true); config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../"))); final BimServer bimServer = new BimServer(config); try { LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), null); bimServer.start(); if (bimServer.getServerInfo().getServerState() == ServerState.NOT_SETUP) { bimServer.getService(AdminInterface.class).setup("http://localhost", "Administrator", "admin@bimserver.org", "admin", null, null, null); } } catch (PluginException e2) { e2.printStackTrace(); } catch (ServerException e) { e.printStackTrace(); } catch (DatabaseInitException e) { e.printStackTrace(); } catch (BimserverDatabaseException e) { e.printStackTrace(); } catch (DatabaseRestartRequiredException e) { e.printStackTrace(); } catch (UserException e) { e.printStackTrace(); } try { final ServiceMap serviceMap = bimServer.getServiceFactory().get(AccessMethod.INTERNAL); ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class); SettingsInterface settingsInterface = serviceMap.get(SettingsInterface.class); final AuthInterface authInterface = serviceMap.get(AuthInterface.class); serviceInterface = bimServer.getServiceFactory() .get(authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL) .get(ServiceInterface.class); settingsInterface.setCacheOutputFiles(true); settingsInterface.setGenerateGeometryOnCheckin(false); final SProject project = serviceMap.getServiceInterface().addProject("test", "ifc2x3tc1"); SDeserializerPluginConfiguration deserializerByName = serviceMap.getServiceInterface() .getDeserializerByName("IfcStepDeserializer"); Path file = Paths.get("../TestData/data/AC11-Institute-Var-2-IFC.ifc"); serviceInterface.checkin(project.getOid(), "test", deserializerByName.getOid(), file.toFile().length(), file.getFileName().toString(), new DataHandler(new FileDataSource(file.toFile())), false, true); final SProject projectUpdate = serviceMap.getServiceInterface().getProjectByPoid(project.getOid()); ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(1000)); for (int i = 0; i < 20; i++) { executor.execute(new Runnable() { @Override public void run() { try { ServiceMap serviceMap2 = bimServer.getServiceFactory().get( authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL); SSerializerPluginConfiguration serializerPluginConfiguration = serviceMap .getServiceInterface().getSerializerByName("Ifc2x3"); Long download = serviceMap2.getServiceInterface().download( Collections.singleton(projectUpdate.getLastRevisionId()), DefaultQueries.allAsString(), serializerPluginConfiguration.getOid(), true); SDownloadResult downloadData = serviceMap2.getServiceInterface() .getDownloadData(download); if (downloadData.getFile() .getDataSource() instanceof CacheStoringEmfSerializerDataSource) { CacheStoringEmfSerializerDataSource c = (CacheStoringEmfSerializerDataSource) downloadData .getFile().getDataSource(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeToOutputStream(baos, null); System.out.println(baos.size()); } catch (SerializerException e) { e.printStackTrace(); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(downloadData.getFile().getInputStream(), baos); System.out.println(baos.size()); } serviceMap2.getServiceInterface().cleanupLongAction(download); } catch (ServerException e) { e.printStackTrace(); } catch (UserException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (PublicInterfaceNotFoundException e1) { e1.printStackTrace(); } } }); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.HOURS); bimServer.stop(); } catch (ServerException e1) { e1.printStackTrace(); } catch (UserException e1) { e1.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (PublicInterfaceNotFoundException e2) { e2.printStackTrace(); } }
From source file:com.example.android.threadsample.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode images. *///from www . jav a 2 s . c o m private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for downloading, using a linked * list queue that blocks when the queue is empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for decoding, using a linked * list queue that blocks when the queue is empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control downloading and * decoding, using a linked list queue that blocks when the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, because it moves photo * Bitmaps from the PhotoTask object to the View object. * To force the Handler to run on the UI thread, it's defined as part of the PhotoManager * constructor. The constructor is invoked when the class is first referenced, and that * happens when the View invokes startDownload. Since the View runs on the UI Thread, so * does the constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming message */ switch (inputMessage.what) { // If the download has started, sets background color to dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is waiting, sets the * background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the * ImageView's bitmap to the bitmap in the * incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }
From source file:com.example.hotnewsapp.imageutil.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images.//from w w w . ja va 2 s .co m */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) { /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } } }; }
From source file:com.comic.lazyupload.image.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images./* w ww . j a va2s . c o m*/ */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ int downloadingImageId = localView.getCustomDownloadingImage(); int failImageId = localView.getCustomFailImage(); if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: Loge.i("DOWNLOAD_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow Loge.i("DOWNLOAD_COMPLETE"); localView.setStatusResource(downloadingImageId); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: Loge.i("DECODE_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: Loge.i("TASK_COMPLETE"); localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: Loge.i("DOWNLOAD_FAILED"); localView.setStatusResource(downloadingImageId); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }